Given a singly linked list l: l0→l1→ ... →ln-1→lN,
Reorder it to: l0→ln→l1→ln-1→l2→l N-2→ ...
You must does this in-place without altering the nodes ' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
It looks a bit difficult, actually it can be divided into several steps.
1. Locate the middle node. Divided into two linked lists. (Available in the algorithm summary)
2. Reverse the second part of the list. (Available in the algorithm summary)
3. Merge two linked lists. (recursive)
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* Reverselist (listnode*head) { A if(head==null| | head->next==NULL) - returnhead; -listnode* p=head->next,*q=head,*l=head; the while(p->next!=NULL) { -L=p->Next; -p->next=Q; -q=p; +p=l; - } +p->next=Q; Ahead->next=NULL; at returnp; - } -listnode* Merge (listnode* l1,listnode*L2) { - if(l1==NULL) - returnL2; - if(l2==NULL) { inl1->next=NULL; - returnL1; to } +listnode* p=l1,*q=L2; -L1=l1->Next; theL2=l2->Next; *p->next=Q; $q->next=Merge (L1,L2);Panax Notoginseng returnp; - } the voidReorderlist (listnode*head) { + if(head==null| | head->next==NULL) A return; thelistnode* p=head,*q=head,*bf=NULL; + while(p&&p->next!=NULL) { -P=p->next->Next; $bf=Q; $Q=q->Next; - } -bf->next=NULL; theq=reverselist (q); - Merge (head,q);Wuyi return; the } -};
[leetcode]143. Reorder List