Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->NULL
,
return 1->3->5->2->4->NULL
.
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
package leetcode328;
public class Solution {
public ListNode oddEvenList(ListNode head) {
ListNode p = head;
if(head==null){
return null;
}
ListNode h2 = null;
ListNode q = p, r1, r2 = null;
ListNode h1 = head;
r1 = h1;
p = p.next;
if (p != null) {
h2 = p;
r2 = h2;
p = p.next;
r2.next=null;
}
int count = 3;
while (p != null) {
q = p.next;
if (count % 2 == 1) {
r1.next = p;
p.next = null;
r1 = p;
count++;
}
p = q;
if (q != null) {
q = q.next;
} else {
break;
}
if (count % 2 == 0) {
r2.next = p;
p.next = null;
r2 = p;
count++;
}
p = q;
}
r1.next=h2;
return h1;
}
public ListNode create(int[] a){
ListNode head = new ListNode(a[0]);
ListNode q = head;
for(int i=1;i<a.length;i++){
ListNode p = new ListNode(a[i]);
q.next=p;
q=p;
}
return head;
}
public void show(ListNode head){
ListNode p = head;
while(p!=null){
System.out.println(p.val);
p = p.next;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = {};
Solution s = new Solution();
ListNode head = s.create(a);
s.show(head);
ListNode h = s.oddEvenList(head);
s.show(h);
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}