链表分成两部分,后一部分翻转,依次加入新的链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
ListNode* split(ListNode* head) {
auto s1 = head;
auto s2 = head;
auto pre = head;
while (s2 && s2->next) {
pre = s1;
s1 = s1->next;
s2 = s2->next->next;
}
return s2? s1 : pre;
}
ListNode* reverse(ListNode *head){
ListNode dummy;
auto p = head;
while (p) {
auto back = p->next;
p->next = dummy.next;
dummy.next = p;
p = back;
}
return dummy.next;
}
public:
void reorderList(ListNode* head) {
if (!head || !head->next) {
return;
}
//分出两部分
auto mid = split(head);
auto front = head;
auto back = mid->next;
mid->next = nullptr;
//后半部分反转
back = reverse(back);
ListNode dummy;
ListNode* tail = &dummy;
// front back 两链表依次填入新的链表中
bool isfront = true;
while (front || back) {
//如果后一个链表为空或者就是要填入前链表
if (!back || (isfront && front)) {
tail->next = front;
tail = tail->next;
front = front->next;
}else{//填充后链表
tail->next = back;
tail = tail->next;
back = back->next;
}
isfront = !isfront;
}
tail->next = nullptr;
}
};