PU Odd Even Linked List

Jan 01, 1970

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.
  • 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 ...

Example:

  • Given 1->2->3->4->5->NULL,
  • return 1->3->5->2->4->NULL.

C Solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* oddEvenList(struct ListNode* head) {
    struct ListNode odd, even, *o = &odd, *e = &even;
    o->next = 0;
    e->next = 0;
    int isodd = 1;
    while (head) {
        if (isodd) {
            o->next = head;
            o = o->next;
        }
        else {
            e->next = head;
            e = e->next;
        }
        isodd ^= 1;
        head = head->next;
    }
    o->next = even.next;
    e->next = 0;
    return odd.next;
}

Python Solution:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def oddEvenList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        ocur = odd = ListNode(0)
        ecur = even = ListNode(0)
        is_ocur = 1
        while head:
            if is_ocur:
                ocur.next = ocur = head
            else:
                ecur.next = ecur = head
            head = head.next
            is_ocur ^= 1
        ecur.next = None
        ocur.next = even.next
        return odd.next

Summary:

  1. 6ms, 8.41%
  2. When it's necessary to record the head and the tail, use dummy and its pointer is suitable.

LeetCode: 328. Odd Even Linked List