This content originally appeared on DEV Community and was authored by Reaper
Intuition: Make two dummy nodes OddHead and EvenHead, all the odd indices goes to OddHead, and even indices go to EvenHead.
Approach:
OddHead will have all the odd ones, EvenHead will have all the even ones
connect them via a pointer.
Java Solution:-
public ListNode oddEvenList(ListNode head){
if(head == null || head.next == null) return head;
ListNode oddHead = new ListNode(-1);
ListNode evenHead = new ListNode(-1);
ListNode oddptr = oddHead;
ListNode evenptr = evenHead;
ListNode current = head;
int index = 1;
while(current!= null){
if(index%2 == 1){
oddptr.next = current;
oddptr = oddptr.next;
}
else{
evenptr.next = current;
evenptr = evenptr.next;
}
current = current.next;
index++;
}
evenptr.next = null;
oddptr.next = evenHead.next;
return oddHead.next;
}
This content originally appeared on DEV Community and was authored by Reaper