Reorder List, Leetcode 解题笔记

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→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}.

思路比较直接,就是先把list分成两段,然后翻转第二段,再把两段合起来。操作中很多地方容易出错,以此写出bug free的代码还是很难的。这里要非常熟悉反转list的操作,不熟的要多练两遍。

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        if(head == null || head.next == null) return;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode secondHead = slow.next;
        slow.next = null;
        ListNode second = reverse(secondHead);
        ListNode cur = head;
        while(second != null){
            ListNode temp = second.next;
            second.next = cur.next;
            cur.next = second;
            cur = second.next;
            second = temp;
        }
    }
    private ListNode reverse(ListNode n){
        if(n == null || n.next == null) return n;
        ListNode cur = n;
        ListNode after = n.next;
        ListNode pre = null;
        while(after != null){
            cur.next = pre;
            pre = cur;
            cur = after;
            after = after.next;
        }
        cur.next = pre;
        n = cur;
        return n;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s