328. Odd Even Linked List
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
.
The odd and even means the position of the LinkedList, not the value of the linkedList
This program intends to see how well you understand the linkedlist.
We need to hold two pointers, one is for the last element of the odd element in the linkedList and q is the second last element in the odd list.
for example
1 2 3 4 5
p,q
P Q
p p.next q q.next
then do one operation
the linkedlist becomes
1 3 2 4 5
public class Solution {
public ListNode oddEvenList(ListNode head) {
if(head == null) return head;
ListNode p = head;
ListNode q = haed;
while(q != null && q.next != null){
q = q.next;
p_next = p.next;
q_next = q.next;
q.next = q_next.next;
q_next.next = p.next;
p.next = q_next;
p = p.next;
}
return head;
}
}