Topic links
Title Requirements:
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}
.
Just see the topic, the first idea came out as follows:
The corresponding program is as follows:
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: One voidReorderlist (listnode*head) { A if(!head | |!head->next | |!head->next->next) - return; - theListNode *start = head, *end =nullptr; - BOOLFlag =true; - while(Start->next && start->next->next) - { + if(flag) -Head =start; +Flag =false; A atEnd =start; -Auto Preend =end; - while(end->next) - { -Preend =end; -End = End->Next; in } - toPreend->next =nullptr; +Auto Next = start->Next; -Start->next =end; theEnd->next =Next; * $Start =Next;Panax Notoginseng } - } the};
View Code
But timed out!!!
Later, reference was made to the general solution of others on the Internet:
1) Use the fast pointer to find the middle node and divide the list into two parts.
2) Reverse the back half of the list, this is also a common problem (list reversal).
3) Merge two linked lists.
The specific procedure is as follows (72MS):
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: One voidReorderlist (listnode*head) { A if(!head | |!head->next | |!head->next->next) - return; - theListNode *slow = head, *fast =head; - while(Fast->next && fast->next->next) - { -slow = slow->Next; +Fast = Fast->next->Next; - } + AListNode *mid = slow->Next; atListNode *prev =nullptr; - while(mid) - { -ListNode *next = mid->Next; -Mid->next =prev; -Prev =mid; inMID =Next; - } toSlow->next =nullptr; + -ListNode *start =head; the BOOLFlag =true; * while(Start &&prev) $ {Panax NotoginsengListNode *next = start->Next; -Start->next =prev; thePrev = prev->Next; +Start->next->next =Next; A the if(flag) +Head =start; -Flag =false; $ $Start =Next; - } - the } -};
Leetcode "Linked list": Reorder list