title :
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} .
Code :
/** 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)return; ListNode Dummy (-1); Dummy.next=Head; ListNode*P1 = &dummy, *P2 = &dummy; //get the mid Node for(; p2 && p2->next; p1 = p1->next, p2 = p2->next->next); //reverse the second half list for(ListNode *prev = p1, *curr = p1->next; Curr && curr->next;) {ListNode*tmp = curr->Next; Curr->next = curr->next->Next; TMP->next = prev->Next; Prev->next =tmp; } //cut the list from mid and merge both list for(P2 = p1->next, P1->next = NULL,P1 =head; p2;) {ListNode*tmp = p1->Next; P1->next =P2; P2= p2->Next; P1->next->next =tmp; P1=tmp; } }};
Tips:
Changed two times, finally the efficiency of AC into 5%.
The idea of the algorithm:
Step1. Locate the middle node (P1 points to the node before the middle node)
Step2. Reverse the latter half of the list
Step3. Speak two lists for the merge operation
Minimizing unnecessary statements in the loop body (such as conditional judgments, assignment statements, and opening new intermediate variables) can improve program efficiency.
"Reorder List" cpp