Leetcode (143): Recorder List

Source: Internet
Author: User

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

Test Instructions: given a list, the last node is inserted behind the first node, the penultimate node is inserted behind the second node of the original list, and so on.

idea: Use the fast pointer method to find the midpoint of the list, then reverse the linked list to the right of the midpoint, then merge the two linked lists.

Code:

 Public voidreorderlist (ListNode head) {if(Head = =NULL|| Head.next = =NULL)return; ListNode Slow=Head; ListNode Fast=Head;  while(Fast.next! =NULL&& Fast.next.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; } ListNode Mid=Slow.next; ListNode cur=mid; ListNode Pre=NULL;  while(cur! =NULL) {ListNode post=Cur.next; Cur.next=Pre; Pre=Last ; Cur=Post; } Slow.next=NULL;  while(Head! =NULL&& Pre! =NULL) {ListNode next1=Head.next; Head.next=Pre; Pre=Pre.next; Head.next.next=Next1; Head=Next1; }            }

Leetcode (143): Recorder 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.