题目描述:
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}.
Hide Tags Linked List
分析:题目是要将链表后面的节点方向间隔插入前面的节点。
那么需要先把拆分为两段,然后将后面部分反转后插入前面部分。
可以利用快慢指针,找到分割点。慢指针每次走一步,快指针每次走两步,那么当快指针走到末尾时,慢指针就是分割点,其之后的节点就是属于后面部分,然后将后
面部分反转后,间隔地插入到前面链表部分。
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}.
Hide Tags Linked List
分析:题目是要将链表后面的节点方向间隔插入前面的节点。
那么需要先把拆分为两段,然后将后面部分反转后插入前面部分。
可以利用快慢指针,找到分割点。慢指针每次走一步,快指针每次走两步,那么当快指针走到末尾时,慢指针就是分割点,其之后的节点就是属于后面部分,然后将后
面部分反转后,间隔地插入到前面链表部分。
以下是C++实现代码:
/**//64ms/*/
/**
* 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 == NULL || head->next == NULL)
return;
ListNode *s = head; //慢指针
ListNode *f = head; //快指针
while(f != NULL && f->next != NULL){
s = s->next;
f = f->next->next;
}
ListNode *rh =s->next; //从rh开始为后边部分
s->next = NULL; //分割出前面部分
ListNode *revers = NULL;
while(rh != NULL) //反转后面部分
{
ListNode *tp = new ListNode(rh->val);
tp->next = revers;
revers = tp;
rh = rh->next;
}
s = head; //指向前面部分
while(revers != NULL){ //一次将后面部分的节点插入到前面的节点中
rh = revers->next; //指向后面部分的节点
revers->next = s->next;
s->next = revers;
s = revers->next;
revers =rh;
}
}
};