Lintcode-medium-reorder List

Source: Internet
Author: User
Tags lintcode

Given a singly linked list l:l0→l1→ ... →ln-1→ln

Reorder It to:l0→ln→l1→ln-1→l2→ln-2→ ...

Example

Given 1->2->3->4->null , reorder it to 1->4->2->3->null .

Challenge

Can do this in-place without altering the nodes ' values?

/*** Definition for ListNode. * public class ListNode {* int val; * ListNode Next; * ListNode (int val) {* This.val = val; * This.next = null; *     } * } */  Public classSolution {/**     * @paramhead:the head of linked list. * @return: void*/     Public voidreorderlist (ListNode head) {//Write your code here                if(Head = =NULL|| Head.next = =NULL|| Head.next.next = =NULL)            return; ListNode Slow=Head; ListNode Fast=Head;  while(Fast! =NULL&& Fast.next! =NULL&& Fast.next.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; } ListNode head2=Slow.next; Slow.next=NULL; Head2=reverse (head2); ListNode P1=Head; ListNode P2=head2; ListNode P1_next=Head.next; ListNode P2_next=Head2.next;  while(P1_next! =NULL&& P2_next! =NULL) {P1.next=P2; P2.next=P1_next; P1=P1_next; P2=P2_next; P1_next=P1_next.next; P2_next=P2_next.next; } P1.next=P2; P2.next=P1_next; return; }         PublicListNode Reverse (listnode head) {if(Head = =NULL|| Head.next = =NULL)            returnHead; ListNode prev=Head; ListNode Curr=Head.next; ListNode Next=Head.next.next; Head.next=NULL;  while(Next! =NULL) {Curr.next=prev; Prev=Curr; Curr=Next; Next=Next.next; } Curr.next=prev; returnCurr; }}

Lintcode-medium-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.