PU Reorder List

Jan 01, 1970

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

  • You must do this in-place without altering the nodes' values.

For example:

  • Given 1,2,3,4, reorder it to 1,4,2,3.

C Solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
void reorderList(struct ListNode* head) {
    if (!head || !head->next) return;
    struct ListNode *l = head, *r = head->next;
    while (r && r->next) {
        l = l->next;
        r = r->next->next;
    }
    r = l->next;
    while (r->next) {
        struct ListNode *tmp = r->next;
        r->next = r->next->next;
        tmp->next = l->next;
        l->next = tmp;
    }
    r = l->next;
    l->next = 0;
    while (r) {
        struct ListNode *tmp = r->next;
        r->next = head->next;
        head->next = r;
        head = r->next;
        r = tmp;
    }
}

Python Solution:

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

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: void Do not return anything, modify head in-place instead.
        """
        if not head or not head.next: return
        slow, fast = head, head.next
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

        tail = slow.next
        while tail.next:
            cur = tail.next
            slow.next, cur.next, tail.next = cur, slow.next, cur.next

        r = slow.next
        slow.next = None
        l = head
        while r:
            tmp = r.next
            l.next, r.next = r, l.next
            l = r.next
            r = tmp

Summary:

  1. 13ms, 70.69%
  2. find the point, reverse the last part, merge.
  3. use tmp, it's necessary.

LeetCode: 143. Reorder List