Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
#include <iostream>
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void reorderList(ListNode* head) {
if(!head) return;
ListNode* slow = head;
ListNode* fast = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
}
//逆置slow开始的链表
//头插法
if(!slow->next)
return;
ListNode* tail = slow->next;
slow->next = NULL;
ListNode* p = tail->next;
tail->next = NULL;
while(p){
ListNode* temp = p->next;
p->next = tail;
tail = p;
p = temp;
}
//按序合并两链表head,tail
while(head && tail){
ListNode* temp_head = head->next;
head->next = tail;
ListNode* temp_tail = tail->next;
tail->next = temp_head;
head = temp_head;
tail = temp_tail;
}
}