1.快慢指针+反转链表
首先使用快慢指针寻找链表中点,然后反转后半部分,然后将后半部分插入到前半部分的间隙中
代码如下:
/**
* 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 *slow=head,*fast=head;
//快慢指针求链表中点,slow:奇数个元素指向中间,偶数个元素指向后半部分第一个元素
while(fast!=NULL&&fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
}
ListNode *middle=slow;
//反转后半部分链表
ListNode *pre=NULL,*next=NULL;
while(slow)
{
next=slow->next;
slow->next=pre;
pre=slow;
slow=next;
}//此时pre指向反转链表的第一个节点
//将后半部分插入前半部分
ListNode *cur=head;
ListNode *node1=cur->next;
ListNode *node2=pre->next;
while(pre!=middle&&cur!=middle)
{
cur->next=pre;
pre->next=node1;
cur=node1;
pre=node2;
node1=cur->next;
node2=pre->next;
}
}
};
2.快慢指针+栈
使用快慢指针寻找到链表中点,然后使用栈存放后半部分元素,然后将栈中元素依次弹出插入到前半部分的间隙中