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}.
void reorderList(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return;
//使用快慢指针找到中间节点
ListNode* slow = head;
ListNode* fast = head;
while(fast->next != nullptr && fast->next->next != nullptr){
fast = fast->next->next;
slow = slow->next;
}
ListNode* mid=slow->next;
//对后半部分进行链表反转
ListNode* last=mid;
ListNode* pre = nullptr;
while(last != nullptr){
ListNode* temp = last->next;
last->next = pre;
pre = last;
last = temp;
}
slow->next = nullptr;
//将两部分的结果合并
while(head != nullptr && pre != nullptr){
ListNode * nxt = head->next;
head->next = pre;
pre = pre->next;
head->next->next = nxt;
head = nxt;
}
}