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

The subject can be seen as the further complex state of reverse Linked List 2, the problem-solving idea is

If the list is 1 2 3 4 5 6 7 8 9

1. Find the middle element of the list

2. Reverse the second half of the list (using reverse Linked the concept of List 2)

3. New Linked List 1 2 3 4 5 9 8 7 6. The list is reordered (also using reverse Linked List 2, the elements in the second half of the list are inserted one by one into the first half, 9 inserted between 1, 2, 8 inserted between 2, 3 ...). )

When solving a problem, a long time debug is performed due to the loss of the moving bit

Therefore, it should be noted that

1. If you remove one of the linked lists, you must save the

2. If one of the linked lists is added, save the next one

/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {val = x;}}} */public class Soluti On {public void reorderlist (ListNode head) {if (head==null| |                Head.next==null) return;        ListNode P1 = head;        ListNode P2 = head;            while (P2.next = null && p2.next.next! = null) {P1 = P1.next;        P2 = p2.next.next;        } listnode pre = P1;        ListNode Curr = P1.next;        ListNode middle = p1;            while (curr.next! = null) {ListNode then = Curr.next;            Curr.next = Then.next;            Then.next = Pre.next;            Pre.next = then;        then = Curr.next;        } ListNode start = head;        ListNode move = Middle.next;            while (start! = middle) {Middle.next = Move.next;            Move.next = Start.next;            Start.next = move;      start = Move.next;      move = Middle.next; }            }}

  

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.