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} .
1, through the double pointer method to get the midpoint of the list, so that the left and right two linked lists
2. Reverse the right half of the list
3. Merge two linked lists
1 voidReorderlist (ListNode *head)2 {3 if(head = = NULL | | head->next = = NULL | | head->next->next = =NULL)4 return;5 6ListNode *p, *q, *dummy =NewListNode (int_min);7Q =head;8p = q->Next;9 while(P! =NULL)Ten { OneQ = q->Next; Ap = p->Next; - if(P! =NULL) -p = p->Next; the } - -Dummy->next = q->next;//Right half nodes -Q->next =NULL; +Q = head;//Left half nodes - reverse (dummy); + A while(Q! =NULL) at { -p = dummy->Next; -Dummy->next = p->Next; -P->next = q->Next; -Q->next =p; -Q = q->Next; inQ = q->Next; - if(Dummy->next = =NULL) to Break; + } -Delete dummy; the } * $ voidReverse (ListNode *dummy)Panax Notoginseng { -ListNode *p = Dummy, *q, *R; the +Q = p->Next; A if(q = =NULL) the return; +r = q->Next; - while(r! =NULL) $ { $Q->next =p; -p =Q; -Q =R; ther = r->Next; - }WuyiQ->next =p; theDummy->next->next =NULL; -Dummy->next =Q; Wu}
Leetcode. Reorder List