Leetcode 143. Reorder 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} .

Analysis:

    1. Break list in the middle to lists (use fast & slow pointers)
    2. Reverse The order of the second list
    3. Merge both list back together

Java Code:

20160601

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { Public voidreorderlist (ListNode head) {//1.find The middle node in the list and split it into the small list//2. Reverse the second list//3. Merge one halves into one long list//Base Case        if(Head = =NULL|| Head.next = =NULL) {            return; } ListNode Mid=Findmiddle (head); ListNode One=Head; ListNode=Mid.next; Mid.next=NULL; both=reverse (both);    Merge (one, both); }        PrivateListNode Findmiddle (ListNode head) {if(Head = =NULL|| Head.next = =NULL) {            returnHead; } ListNode Slow= Head, fast =Head;  while(Fast.next! =NULL&& Fast.next.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; }        returnslow; }        PrivateListNode Reverse (listnode head) {//Iteration        if(Head = =NULL|| Head.next = =NULL) {            returnHead; } ListNode Pre=NULL; ListNode cur=Head;  while(cur! =NULL) {ListNode next=Cur.next; Cur.next=Pre; Pre=cur; Cur=Next; }        returnPre; }        Private voidMerge (ListNode one, ListNode) { while(Both! =NULL) {ListNode next1=One.next; ListNode next2=Two.next; One.next=both ; Two.next=Next1; One=Next1; both=next2; }    }}

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.