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}.
先通过快慢指针找到转换节点,将转换节点后半部分逆序,然后再将转换节点依次插入前半部分即可。
代码如下:
/**
* 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,*p2;
p1 = p2 = head;
while(p2->next && p2->next->next)
{
p1 = p1->next;
p2 = p2->next->next;
}
ListNode* cur = p1->next;
ListNode* next;
while(cur->next)
{
next = cur->next;
cur->next=next->next;
next->next = p1->next;
p1->next = next;
}
p2 = head;
cur = p1->next;
while(p2!=p1)
{
p1->next = cur->next;
cur->next = p2->next;
p2->next = cur;
p2 = cur->next;
cur = p1->next;
}
}
};
本文介绍了一种在不改变链表节点值的情况下,对链表进行特定重排序的方法。通过使用快慢指针找到中间节点,然后逆序后半部分链表,并交替地将后半部分的节点插入到前半部分之中。
364

被折叠的 条评论
为什么被折叠?



