Leetcode 143. Reorder List

Posted 茜茜的技术空间

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 143. Reorder List相关的知识,希望对你有一定的参考价值。

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: 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 to {1,4,2,3}.


Analysis:

  1. Break list in the middle to two lists (use fast & slow pointers)
  2. Reverse the order of the second list
  3. Merge two list back together

Java code:

20160601

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        //1.find the middle node in the list and split it into two small list
        //2. reverse the second list
        //3. merge two halves into one long list
        
        //base case
        if(head == null || head.next == null) {
            return;
        }
        
        ListNode mid = findMiddle(head);
        ListNode one = head;
        ListNode two = mid.next;
        mid.next = null;
        two = reverse(two);
        merge(one, two);
    }
    
    private ListNode findMiddle(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode slow = head, fast = head;
        while(fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    
    private ListNode reverse(ListNode head) {
        //iteration
        if(head == null || head.next == null) {
            return head;
        }
        ListNode pre = null;
        ListNode cur = head;
        while(cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
    
    private void merge(ListNode one, ListNode two) {
        while(two != null) {
            ListNode next1 = one.next;
            ListNode next2 = two.next;
            one.next = two;
            two.next = next1;
            one = next1;
            two = next2;
        }
    }
}

 

以上是关于Leetcode 143. Reorder List的主要内容,如果未能解决你的问题,请参考以下文章

leetcode143- Reorder List问题

143. Reorder List - LeetCode

LeetCode 143. Reorder List

Leetcode 143. Reorder List

LeetCode-143-Reorder List

LeetCode 143. Reorder List