Wednesday, June 8, 2016

Leetcode: 328. Odd Even Linked List

iven 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.
Solution:
The problem has two cases to consider: the length of the list is even and odd, respectively. 
We use two pointers, p1 and p2, to trace the odd and even nodes, respectively. If the length of the list is even, we stop at p2.next == null, i.e, when p2 reaches to the last node. In this case, p1 is in the node next to the last. e.g.
1 -> 2 -> 3 -> 4 -> null
               |      |
             p1    p2

If the length of the list is odd, we stop at p2 == null, i.e, p1 is in the last node. 
1 -> 2 -> 3 -> 4 -> 5 -> null
                              |      |
                             p1   p2

We can observe that p1 is always one step below the p2, and we must let p1 stop at the last node of the odd list, then finally p1.next = evenHead. That is, we cannot lose the tail of the odd list, i.e., let p1 = null. 

Code (Java):
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode odd = head;
        ListNode even = head.next;
        ListNode evenHead = even;
        
        while (even != null && even.next != null) {
            odd.next = even.next;
            odd = odd.next;
            
            even.next = odd.next;
            even = even.next;
        }
        
        odd.next = evenHead;
        
        return head;
    }
}




No comments:

Post a Comment