题目
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}.
思路
先找到中间节点,然后反转中间节点以后的节点,得到新的反转子链表,然后循环插入到原链表中即可。
代码
class Solution {
public:
void reorderList(ListNode* head) {
if(NULL == head || NULL == head->next)
return;
///找到中间节点
ListNode *p_fast = head->next, *p_slow = head;
while(p_fast && p_fast->next) {
p_fast = p_fast->next->next;
p_slow = p_slow->next;
}
///反转
ListNode *p = p_slow->next, *q = p->next, *t;
p_slow->next = NULL;
p->next = NULL;
while (q) {
t = q->next;
q->next = p;
p = q;
q = t;
}
ListNode *ptr = head;
while(p){
ListNode *temp = p->next;
p->next = ptr->next;
ptr->next = p;
ptr = ptr->next->next;
p = temp;
}
}
};