一、题目解析

1、不能单纯改变节点内部的值,要改变节点的指针
2、节点个数为[1,5*10^4]
二、算法原理
解法:模拟

对于上面的重排,我们可以将其拆解为两个链表合并,后面一个链表需要逆置,而分割的位置正好处于原链表的中间节点,由此我们可以模拟这个过程来重拍链表
1、找到链表的中间节点
快慢指针法

2、把后面的部分逆置
三指针头插法

只需按顺序链接即可,newhead->next = slow,slow->next = tail,tail = slow
3、合并两个链表
以一个哨兵为头节点,依次尾插即可,最后delete哨兵位头节点即可
画图可以解决指针链接问题,链表问题建议多画图
三、代码示例
cpp
class Solution {
public:
void reorderList(ListNode* head)
{
ListNode* cur1 = head,*cur2 = head;
//找中间
while(cur2 && cur2->next)
{
cur1 = cur1->next;
cur2 = cur2->next->next;
}
//逆序后面(头插三指针)
ListNode* newhead2 = new ListNode();
newhead2->next = cur1;
ListNode* cnext = cur1->next;
cur1->next = nullptr;
while(cnext)
{
ListNode* nnext = cnext->next;
newhead2->next = cnext;
cnext->next = cur1;
cur1 = cnext;
cnext = nnext;
}
//合并
ListNode* newhead1 = new ListNode();
ListNode* tail = newhead1;
while(cur1)
{
tail->next = head;
tail = head;
if(head->next == nullptr) break;
head = head->next;
tail->next = cur1;
tail = cur1;
cur1=cur1->next;
}
//释放哨兵位头节点
delete newhead1;
delete newhead2;
}
};
