您的位置:首页 > 其它

Leetcode 143 Reorder List

2016-11-18 16:28 295 查看
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}
.
将链表对半分割,后半部分逆置后与前半部分交叉合并,模拟,没什么好说的。
注意小细节,不然会像我一样疯狂RE

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if (!head || !head->next) return;
ListNode* p1 = head;
ListNode* p2 = head->next;
while (p2 && p2->next)
{
p1 = p1->next;
p2 = p2->next->next;
}
ListNode* head2 = p1->next;
p1->next = NULL;
p2 = head2->next;
head2->next = NULL;
while (p2)
{
p1 = p2->next;
p2->next = head2;
head2 = p2;
p2 = p1;
}
p1 = head;
p2 = head2;
while(p2)
{
ListNode* t1 = p1;
ListNode* t2 = p2;
p1 = p1->next;
t1->next = p2;
p2 = p2->next;
t2->next = p1;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: