143. Reorder List [LeetCode]

143Reorder List

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

先对半拆分链表,逆序后面的链表,然后merge成一个链表.

为了便于复习,我把三种链表反转的函数都列出来了.

链表反转见LeetCode:206Reverse Linked List.我整理的相应的解答

class Solution_143_1 {
public:
     void reorderList(ListNode* head) {
         if (head == nullptr || head-> next == nullptr) return;

        ListNode*slow = head, *fast = head, *prev = nullptr;
         while (fast&&fast-> next) {
            prev = slow;
            slow = slow-> next;
            fast = fast-> next-> next;
        }
        prev-> next = nullptr; //cut at middle
        slow= reverse_3(slow);
         //merge
        ListNode*curr = head;
         while (curr-> next) {
            ListNode*tmp = curr-> next;
            curr-> next = slow;
            slow = slow-> next;
            curr-> next-> next = tmp;
            curr = tmp;
        }
        curr-> next = slow;
    }

     //复习一下链表反转
    ListNode* reverse_1(ListNode*head) {
         if (head == nullptr || head-> next == nullptr) return head;
        ListNode*prev = head;
         for (ListNode*curr = prev-> next, *next = curr-> next;
            curr;
            prev = curr, curr = next, next = next ? next-> next : nullptr) {
            curr-> next = prev;
        }

        head-> next = nullptr;
         return prev;    
    }
    ListNode* reverse_2(ListNode*head) {
         if (head == nullptr || head-> next == nullptr) return head;
        ListNode*prev = head;
        ListNode*pcur = prev-> next;

         while (pcur) {
            ListNode*pnext = pcur-> next;
            pcur-> next = prev;
            prev = pcur;
            pcur = pnext;
        }
        head-> next = nullptr;
         return prev;
    }
    ListNode* reverse_3(ListNode* head) {
         if (head == nullptr || head-> next == nullptr) return head;
        ListNode *p = reverse_3(head-> next);
        head-> next-> next = head;
        head-> next = nullptr;
         return p;

    }
};

你可能感兴趣的:(LeetCode解题笔记)