Reorder-list-leetcode

Source: Internet
Author: User

Reorder-list Topic Description

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

Ideas
    1. According to test instructions, a linked list is inserted from the back to the front of the past to insert the linked list, you can divide the list into two parts: the front of the binate back, the latter part from the forward, so that the latter part of the "stack" of the storage structure
    2. Want to use a two-step number of different pointers to divide the list into two parts, so that the results according to the list of nodes of the odd and even different, the number of linked list is less than equal to the previous. Then use the stack to store the linked list, and then traverse the previous list to insert the node.
Code
Import java.util.arraydeque;/** * DefinitionFor singly-linked list. *Class ListNode {*int Val; * ListNodeNext * ListNode (int x) {* val = x; *Next =Null * } * } */PublicClass Solution {public void Reorderlist (ListNode head) {if (head = =null | | Head.Next = =NULL) {return;} arraydeque<listnode> stack =New Arraydeque<listnode> (); ListNode pre = head; ListNode follow = head.Nextwhile (follow.Next! =null) {pre = pre. next;follow = follow. next; if (Follow. Next! = null) {follow = Follow. Next;}} Follow = Pre. next;pre. next = null;pre = Head; while (Follow! = null) {Stack.push (follow); follow = Follow. Next;} while (!stack. IsEmpty ()) {ListNode temp = Stack.pop (); Temp. Next = Pre. next;pre. next = Temp;pre = temp. next;} }} 

Reorder-list-leetcode

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.