Given a singly linked list l:l0→l1→ ... →LN-1→LN,
Reorder It to:l0→ln→l1→ln-1→l2→ln-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}.
Idea: Divide the list into two halves, then flip the back half, and the last one to make up the new linked lists.
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x ): Val (x), Next (NULL) {}}; */Class Solution { Public:voidReorderlist (ListNode*Head) {if(Head==NULL ||Head -Next==NULL)return; ListNode*Mid=Getmid (head); ListNode*Left=Head*Right=Reverselist (mid -Next); Mid -Next= NULL; ListNode*Newhead= NewListNode (-1); ListNode*Newtail=Newhead; while(left&&right) {ListNode*Temp=Left -Next Left -Next=Newtail -Next Newtail -Next=Left Newtail=Newtail -Next Left=Temp Temp=Right -Next Right -Next=Newtail -Next Newtail -Next=Right Newtail=Newtail -Next Right=Temp }if(left) Newtail -Next=Leftif(right) Newtail -Next=Right Newhead=Newhead -Next Head=Newhead; }//reverse ListListNode*Reverselist (ListNode*Head) {if(Head==NULL ||Head -Next==NULL)returnHead ListNode*Pre=Head ListNode*NewList= NewListNode (-1); while(Pre!=NULL) {ListNode*Temp=Pre -Next Pre -Next=NewList -Next NewList -Next=Pre Pre=Temp } newlist=NewList -NextreturnNewList; }//get the middle elementListNode*Getmid (ListNode*Head) {if(Head==NULL ||Head -Next==NULL)returnHead ListNode*First=Head*Second=Head -Next while(second&&Second -Next) {First=First -Next Second=Second -Next -Next }returnFirst }};
Leetcode[143]-reorder List