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

Problem solving idea One:

Each time ln is changed to the front, I get l0→lnl1→l2→L3→, Then use the same operation for L1, the Java implementation is as follows:

public void Reorderlist (ListNode head) {ListNode headcopy = head;while (headcopy! = NULL && headcopy.next! = null& amp;& HeadCopy.next.next! = null) {ListNode temp = headcopy;while (Temp.next.next! = null) temp = TEMP.NEXT;TEMP.NEXT.N ext = Headcopy.next;headcopy.next = Temp.next;temp.next = Null;temp = Headcopy.next.next;headcopy=headcopy.next.next;}}

Results tle

Two ways to solve problems:

Space change time, all of the node is stored in a list, and then each operation of the list two node, the Java implementation is as follows:

    public void Reorderlist (ListNode head) {linkedlist<listnode> list = new linkedlist<listnode> (); ListNode headcopy = Head,end = Head;while (headcopy! = null) {List.add (headcopy); headcopy = Headcopy.next;} while (List.size () >2) {headcopy=list.poll (); End=list.get (List.size ()-1); List.remove (List.size ()-1); Headcopy.next=end;end.next=list.peek (); List.get (List.size ()-1). Next=null;}    }

Java for 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.