您的位置:首页 > 其它

[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}.

/*
* 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;
}
}
};




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: