The implementation list is as follows:
Given a singly linked list l: l0→l1→ ... →ln-1→lN,
Reorder it to: l0→ln→l1→ln-1→l2→l N-2→ ...
At first think of an n-side, that is, each time to find the last callback to the corresponding position, and then the penultimate second of the next null, and so on. Sure enough to time out.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: voidReorderlist (ListNode *head) { if(!head | |!head->next)return ; ListNode*cur, *last, *next_cur, *Pre_last; Last= HeadNext; Pre_last=Head; while(Lastnext) {Pre_last=Last ; Last= LastNext; } cur=Head; Next_cur= HeadNext; while(cur, next | | | cur-NEXT! =Last ) {curNext =Last ; Pre_lastNext =NULL; Cur=next_cur; Next_cur= curNext; Last= curNext; Pre_last=cur; while(Last && lastnext) {Pre_last=Last ; Last= LastNext; } } return ; }};View Code
You can also use Map<int, listnode*> to do it, but the use of other space. The following is a more straightforward solution that does not use extra space.
In two halves, the back half reversed, and then two halves before merging.
It is important to note that the last half of the previous one remembers assignment null, and if it is an odd number, the first half should be one more. Give yourself a sample of 1234 and 12345 to see how the merger is divided.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: voidReorderlist (ListNode *head) { if(!head | |!head-NEXT)return ; ListNode*slow = head, *quick = headNext; while(Quick && Quick Next)//divided into two parts{Slow= SlowNext; Quick= QuickNext; if(!Quick) Break; Quick= QuickNext; } Quick= SlowNext; ListNode*last = QuickNext; while(last)//reverse the back half of the{QuickNext = LastNext; LastNext = SlowNext; SlowNext =Last ; Last= QuickNext; } Quick= SlowNext; SlowNext =NULL; ListNode*next_cur = Head, Next, *next_quick, *cur =Head; while(cur && quick)//Merge two parts{curNext =Quick; Next_quick= QuickNext; QuickNext =next_cur; Quick=Next_quick; Cur=next_cur; if(cur) next_cur= curNext; } } };
Leetcode Reorder List