328 Odd Even Linked List

1. Question

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: Given1->2->3->4->5->NULL, return1->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 ...

2. Implementation

1
/**
2
* Definition for singly-linked list.
3
* public class ListNode {
4
* int val;
5
* ListNode next;
6
* ListNode(int x) { val = x; }
7
* }
8
*/
9
class Solution {
10
public ListNode oddEvenList(ListNode head) {
11
if (head == null || head.next == null) {
12
return head;
13
}
14
15
ListNode oddHead = new ListNode(0);
16
ListNode evenHead = new ListNode(0);
17
ListNode p1 = oddHead;
18
ListNode p2 = evenHead;
19
20
ListNode curNode = head;
21
int count = 1;
22
23
while (curNode != null) {
24
if (count % 2 != 0) {
25
p1.next = curNode;
26
p1 = p1.next;
27
}
28
else {
29
p2.next = curNode;
30
p2 = p2.next;
31
}
32
++count;
33
curNode = curNode.next;
34
}
35
p2.next = null;
36
p1.next = evenHead.next;
37
return oddHead.next;
38
}
39
}
Copied!

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)