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} .
Hide TagsLinked List If you use extra space, it is easy to implement, determine the middle position, then put the stack behind, and then build the list from the new. The space is O (n). If you do not use the extra space, the stack space is implemented recursively, which makes the logic more complex. Ideas:
- Determines the point at which the linked list is separated.
- Enter the recursive function, recursively to the end of the second half of the paragraph.
- The recursive function returns the money construct linked list.
This is a lot of detail, such as determining the point of separation, if node=4,
1 2 3 4-1 4 2 3.
So the position of the disconnection is actually the third from the left, and node=5, the same disconnection position is also the third left, the one step method is to use a slow index, first move 1 steps, then slow down one step, and finally move one step, so that no additional variables.
while (1) { if(fast->next!=null) fast=fast->next; Else Break ; Slow=slow->next; if (fast->next!=null) Fast=fast->next; Else Break ; }
Then there is the recursive function, because it is a single linked list, and the variables passed are
void help_f (listnode * &lft,listnode * RGT)
The previous one has a reference, the latter does not, because the constraints of the single index, the first half of the need to constantly move back, can be the same, so that the space is saved, the second half need to use variable tags each time, so the index is not able to use.
The final code is as follows, the time is very good 26ms, the ranking statistics are not shown in the previous:
#include <iostream>#include<queue>using namespacestd;/** * Definition for singly-linked list.*/structListNode {intVal; ListNode*Next; ListNode (intx): Val (x), Next (NULL) {}};classSolution { Public: voidReorderlist (ListNode *head) { if(Head==null)return; ListNode*fast=head,*slow=Head; while(1){ if(fast->next!=null) fast=fast->Next; Else Break; Slow=slow->Next; if(fast->next!=null) fast=fast->Next; Else Break; } ListNode* fnl_end=slow; Fast=Fnl_end; Slow=Head; Help_f (Slow,fast); Fnl_end->next=NULL; return ; } voidHelp_f (ListNode * &lft,listnode *RGT) { if(rgt!=null) Help_f (lft,rgt->next); Else return ; RGT->next=lft->Next; LfT->next=RGT; LfT=rgt->Next; }};intMain () {ListNode N1 (1), N2 (2), N3 (3), N4 (4), N5 (5); N1.next=&N2; N2.next=&N3; N3.next=&N4;//n4.next=&n5;solution Sol; Sol.reorderlist (&N1); ListNode*tmp = &N1; while(tmp!=NULL) {cout<<tmp->val<<Endl; TMP=tmp->Next; } return 0;}
[Leetcode] Reorder list Reverse Insert linked list