143. Reorder List (list)

Source: Internet
Author: User

Given a singly linked list l: l0→l1→ ... →ln-1→lN,
Reorder it to: l0→lnl1→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} .

classSolution { Public:    voidReorderlist (ListNode *head) {        if(!head| |!head->next)return; //partition the list into 2 sublists of equal lengthListNode *slownode = head, *fastnode =Head;  while(fastnode->next) {Fastnode= fastnode->Next; if(fastnode->next) {Fastnode= fastnode->Next; } Else {                   Break; } Slownode= slownode->Next; }          //2 sublist HeadsListNode *head1 = head, *head2 = slownode->Next; //Detach the sublistsSlownode->next =NULL; //reverse the second sublistListNode *cur = head2, *post = cur->Next; Cur->next =NULL;  while(POST) {ListNode* Temp = post->Next; Post->next =cur; Cur=Post; Post=temp; } head2= cur;//The new head of the reversed sublist//Merge the 2 sublists as requiredlistnode* p = head1, *q =head2;  while(q) {ListNode*TEMP1 = p->Next; ListNode*TEMP2 = q->Next; P->next =Q; Q->next =Temp1; P=Temp1; Q=Temp2; }      }  };

143. Reorder List (list)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.