otal accepted:54991 Total submissions:252600 difficulty:medium
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} .
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Reverselist (listnode*head) {ListNode* cur =Head; ListNode* Newhead =NULL; ListNode* Next =NULL; while(cur) {Next= cur->Next; Cur->next =Newhead; Newhead=cur; Cur=Next; } returnNewhead; } voidReorderlist (listnode*head) { if(Head==null | | head->next==NULL) { return; } ListNode* Slow =Head; ListNode* Fast =Head; ListNode* Pre =NULL; while(FAST) {Pre=slow; Slow= slow->Next; Fast->next? Fast = Fast->next->next:fast =NULL; } Pre->next =NULL; ListNode* Head2 =reverselist (slow); ListNode* cur =Head; ListNode* Cur_next =NULL; ListNode* CUR2 =head2; ListNode* Cur2_next =NULL; while(CUR2) {Cur_next= cur->Next; Cur2_next= cur2->Next; Cur->next =CUR2; CUR2->next =Cur_next; Cur=Cur_next; CUR2=Cur2_next; } }};Next challenges: (m) Partition list (m) Convert Sorted list to Binary Search Tree (H) Copy list with Random Pointer
[Linked List] Reorder List