Leetcode[143]-reorder List

Source: Internet
Author: User

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

Idea: Divide the list into two halves, then flip the back half, and the last one to make up the new linked lists.

/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x ): Val (x), Next (NULL) {}}; */Class Solution { Public:voidReorderlist (ListNode*Head) {if(Head==NULL ||Head -Next==NULL)return; ListNode*Mid=Getmid (head); ListNode*Left=Head*Right=Reverselist (mid -Next); Mid -Next= NULL; ListNode*Newhead= NewListNode (-1); ListNode*Newtail=Newhead; while(left&&right) {ListNode*Temp=Left -Next Left -Next=Newtail -Next Newtail -Next=Left Newtail=Newtail -Next Left=Temp Temp=Right -Next Right -Next=Newtail -Next Newtail -Next=Right Newtail=Newtail -Next Right=Temp }if(left) Newtail -Next=Leftif(right) Newtail -Next=Right Newhead=Newhead -Next Head=Newhead; }//reverse ListListNode*Reverselist (ListNode*Head) {if(Head==NULL ||Head -Next==NULL)returnHead ListNode*Pre=Head ListNode*NewList= NewListNode (-1); while(Pre!=NULL) {ListNode*Temp=Pre -Next Pre -Next=NewList -Next NewList -Next=Pre Pre=Temp } newlist=NewList -NextreturnNewList; }//get the middle elementListNode*Getmid (ListNode*Head) {if(Head==NULL ||Head -Next==NULL)returnHead ListNode*First=Head*Second=Head -Next while(second&&Second -Next) {First=First -Next Second=Second -Next -Next }returnFirst }};

Leetcode[143]-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.