[Leetcode] reorder list

Source: Internet
Author: User
Reorder list

Given a singly linked listL:L0 →L1 →... →LN-1 →LN,
Reorder it:L0 →LNL1 →LN-1 →L2 →LN-2 →...

You must do this in-place without altering the nodes 'values.

For example,
Given{1,2,3,4}, Reorder it{1,4,2,3}.

Algorithm ideas:

Set the speed pointer to separate the first half and the second half, then sort the second half in reverse order, and insert the first half one by one. The time complexity is O (n), and the space complexity is variable.

Thought 1:

In reverse order of the second half, set three pointers to reverse order based on the original list, space complexity O (1)

There are still some questions that will be used here, so this will not be implemented here.

 

Idea 2:

The reverse order of the second half. With stack and space complexity O (n), the code is simple.

The Code is as follows:

 1 public class Solution { 2     public void reorderList(ListNode head) { 3         if(head == null || head.next == null) return ; 4         ListNode hhead = new ListNode(0); 5         hhead.next = head; 6         ListNode fast = hhead; 7         ListNode slow = hhead; 8         while(fast != null && fast.next != null){ 9             fast = fast.next.next;10             slow = slow.next;11         }12         ListNode stackPart = slow.next;13         slow.next = null;14         Stack<ListNode> stack = new Stack<ListNode>();15         while(stackPart != null){16             stack.push(stackPart);17             stackPart = stackPart.next;18         }19         ListNode insert = head;20         while(!stack.isEmpty()){21             ListNode tem = stack.pop();22             tem.next = insert.next;23             insert.next = tem;24             insert = tem.next;25         }26     }27 }

 

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.