首页 > 代码库 > 【Leetcode】Reorder List

【Leetcode】Reorder List

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→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}.

快慢指针找到链表中点,将链表分为两段,翻转后半段,再合并两个子链表。

 1 /** 2  * Definition for singly-linked list. 3  * struct ListNode { 4  *     int val; 5  *     ListNode *next; 6  *     ListNode(int x) : val(x), next(NULL) {} 7  * }; 8  */ 9 class Solution {10 public:11     void reorderList(ListNode *head) {12         if (head == nullptr || head->next == nullptr || head->next->next == nullptr) {13             return;14         }15         ListNode *fast = head, *slow = head;16         while (fast->next && fast->next->next) {17             fast = fast->next->next;18             slow = slow->next;19         }20         fast = slow->next;21         slow->next = nullptr;22         fast = reverseList(fast);23         head = mergeList(head, fast);24     }25 private:26     ListNode * reverseList(ListNode *head) {27         ListNode dummy(-1);28         ListNode *p = &dummy;29         while (head) {30             ListNode *temp = head->next;31             head->next = p->next;32             p->next = head;33             head = temp;34         }35         return dummy.next;36     }37     38     ListNode *mergeList(ListNode *l1, ListNode *l2) {39         ListNode dummy(-1);40         ListNode *p = &dummy;41         while (l1) {42             p->next = l1;43             l1 = l1->next;44             p = p->next;45             if (l2) {46                 p->next = l2;47                 l2 = l2->next;48                 p = p->next;49             }50         }51         return dummy.next;52     }53 };

 

【Leetcode】Reorder List