STRUCTURES XL Total creditl Group nodes by their index: lfthere is a singly link
ID: 3827818 • Letter: S
Question
STRUCTURES XL Total creditl Group nodes by their index: lfthere is a singly linked list, based on indexes, group all nodes with odd index first followed a by the nodes with even index. Example: Given a- 1- 2- 3- 5- NULL >4- return 1- 3- 5- 0- 2- 4 NULL. Notes 1.We are talking about the node number(index) and not the value in the nodes. 2. The relative order inside both the even and odd groups should remain as it was in the input. 3, The first node is considered even, the second node odd and so on... you can solve the above problem easily, you can try to solve it with one more request solve the problem above "in place" You can find the definition of "in place" in https llen, wikipedia orgwikilin place algorithm MacBook AirExplanation / Answer
class ListNode
{
int val;
ListNode next;
ListNode(int x)
{
val = x;
next = null;
}
}
public class Solution {
public ListNode oddEvenList(ListNode head)
{
if(head == null)
return head;
ListNode temp1 = head;
ListNode temp2 = head.next;
ListNode nextHead = temp2;
ListNode nexttail = temp1;
if(nextHead == null)
return head;
while(temp1 != null && temp2 != null)
{
temp1.next = temp2.next;
if (temp1.next != null)
{
temp2.next = temp1.next.next;
}
else
break;
temp1 = temp1.next;
if (temp2.next != null)
temp2 = temp2.next;
}
temp2.next = nexttail;
return nextHead;
}
public static void main(String[] args)
{
Solution s = new Solution();
ListNode head = new ListNode(0);
ListNode tmp = new ListNode(1);
head.next = tmp;
ListNode tmp1 = new ListNode(2);
tmp.next = tmp1;
ListNode tmp2 = new ListNode(3);
tmp1.next = tmp2;
ListNode tmp3 = new ListNode(4);
tmp2.next = tmp3;
ListNode tmp4 = new ListNode(5);
tmp3.next = tmp4;
head = s.oddEvenList(head);
while(head != null)
{
System.out.println(head.val);
head = head.next;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.