[Linked List] Reorder List

Source: Internet
Author: User

otal accepted:54991 Total submissions:252600 difficulty:medium

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} .

/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Reverselist (listnode*head) {ListNode* cur =Head; ListNode* Newhead =NULL; ListNode* Next =NULL;  while(cur) {Next= cur->Next; Cur->next =Newhead; Newhead=cur; Cur=Next; }        returnNewhead; }        voidReorderlist (listnode*head) {        if(Head==null | | head->next==NULL) {            return; } ListNode* Slow =Head; ListNode* Fast =Head; ListNode* Pre =NULL;  while(FAST) {Pre=slow; Slow= slow->Next; Fast->next? Fast = Fast->next->next:fast =NULL; } Pre->next =NULL; ListNode* Head2 =reverselist (slow); ListNode* cur =Head; ListNode* Cur_next =NULL; ListNode* CUR2 =head2; ListNode* Cur2_next =NULL;  while(CUR2) {Cur_next= cur->Next; Cur2_next= cur2->Next; Cur->next =CUR2; CUR2->next =Cur_next; Cur=Cur_next; CUR2=Cur2_next; }    }};
Next challenges: (m) Partition list (m) Convert Sorted list to Binary Search Tree (H) Copy list with Random Pointer

[Linked List] Reorder 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.