[LeetCode] 143. Reorder List
2017-07-08 19:12
302 查看
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}.
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}.
/* * step 1: 将链表一分为二,slow、fast两个指针,slow每次移动一个位置,fast每次移动两个位置 * step 2: 将后半部的链表,反转 * step 3: 按照题目中的要求,合并两部分链表 */ class Solution { public: void reorderList(ListNode* head) { if (head == nullptr || head->next == nullptr) return; ListNode *sndhlf = SecondHalf(head); ListNode *revsndhalf = Reverse(sndhlf); MergeList(head, revsndhalf); } private: ListNode *SecondHalf(ListNode *head) { ListNode *slow, *fast; slow = fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; } ListNode *res = slow->next; slow->next = nullptr; return res; } ListNode *Reverse(ListNode *head) { ListNode *prev = nullptr; while (head) { ListNode *cur = head; head = head->next; cur->next = prev; prev = cur; } return prev; } void MergeList(ListNode *head1, ListNode *head2) { int CurChoice = 0; ListNode *heads[] = {head1, head2}; while (heads[1] != nullptr) { ListNode *cur = heads[CurChoice]; heads[CurChoice] = heads[CurChoice]->next; cur->next = heads[!CurChoice]; CurChoice = !CurChoice; } } };
相关文章推荐
- [LeetCode] 143. Reorder List
- LeetCode 143. Reorder List
- Leetcode-143. Reorder List
- 【Leetcode】143. Reorder List - 链表重排序
- 【LeetCode】 143. Reorder List
- [leetcode] 【链表】143. Reorder List
- 【Leetcode】143. Reorder List
- [LeetCode]143. Reorder List
- LeetCode 143. Reorder List
- [Leetcode] 143. Reorder List 解题报告
- Leetcode- 143. Reorder List
- leetcode143. Reorder List
- leetcode 143. Reorder List
- LeetCode 143. Reorder List
- [leetcode]143. Reorder List
- LeetCode143. Reorder List
- LeetCode 143. Reorder List
- *Leetcode 143. Reorder List | 链表
- LeetCode 143. Reorder List
- Leetcode 143. Reorder List