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.
/**
* 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) {
// Split to two parts
if(!head||head->next==NULL)
return;
ListNode *list1, *list2,*p,*q;
list1=p=q=head;
while(q&&q->next&&q->next->next){
p = p->next;
q = q->next->next;
}
ListNode *mid = p->next;
p->next = NULL;
//reverse the second part
ListNode *q1,*q2,*q3;
q1 = mid;
if(mid->next){
q2=mid->next;
while(q2){
q3 = q2->next;
q2->next = q1;
q1 = q2;
q2 = q3;
}
}
mid->next = NULL;
list2 = q1;
//merge the two parts
ListNode *s1,*s2,*s3;
s3 = list1;
s2 = list2;
s1 = list1->next;
while(s1&&s2){
s3->next=s1;
s3->next->next=s2;
s3=s2;
s1=s1->next;
s2=s2->next;
}
if(s1)
s3->next=s1;
if(s2)
s3->next=s2;
}
};