-
题目:Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}. -
idea:
- 首先分析题目,题目等价于将原来链表分为两半 l i s t 1 list_1 list1和 l i s t 2 list_2 list2,后半部分 l i s t 2 list_2 list2反转以后 l i s t 2 ′ list_2^{'} list2′。将 l i s t 1 list_1 list1和 l i s t 2 ′ list_2^{'} list2′交替插入。
- 使用快指针和满指针找到链表的中心结点。此时slow指向前一半的最后一个结点。将slow后边的另一半反转
- 交替插入两个链表
/**
* 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) return;
auto fast = head, slow = head;
while (fast->next && fast->next->next){
fast = fast->next->next;
slow = slow->next;
}
ListNode* p = slow->next;
slow->next = 0;
ListNode *dummy = new ListNode(0);
ListNode* post = 0, *temp = 0, *temp2=0;
while (p){
dummy->next = p;
temp = p->next;
p->next = post;
post = p;
p = temp;
}
auto p1 = head, p2 = dummy->next;
while (p1 && p2){
temp = p1->next;
p1->next = p2;
temp2 = p2->next;
p2->next = temp;
p1 = temp;
p2 = temp2;
}
return;
}
};