Leetcode - Reorder List

Screenshot from 2016-01-29 20:41:16.png

My code:

/**
 * 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) {
        if (head == null || head.next == null)
            return;
        /** divide this linked list into left and right sub list */
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next;
            fast = fast.next;
        }
        
        ListNode left = head;
        ListNode right = slow.next;
        slow.next = null;
        /** reverse the right sub list */
        right = reverse(right);
        /** merge these two sub list to get result */
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode curr = dummy;
        while (left != null && right != null) {
            curr.next = left;
            left = left.next;
            curr = curr.next;
            curr.next = right;
            curr = right;
            right = right.next;
        }
        if (left != null)
            curr.next = left;
    }
    
    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode pre = head;
        ListNode curr = head.next;
        while (curr != null) {
            ListNode temp = curr.next;
            curr.next = pre;
            pre = curr;
            curr = temp;
        }
        head.next = null;
        return pre;
    }
}

这道题木一遍过。其实本身不是很难的。
思路如下:
首先找到中点,将链表一分为二。切断联系!
然后 reverse right sub list
最后, merge 这两个sub list
就做出来了。

看了下,时间测试不是很好。然后查了下programcreek,做法和我相同。讲解的更好。
把网址贴在这里:
http://www.programcreek.com/2013/12/in-place-reorder-a-singly-linked-list-in-java/

Anyway, Good luck, Richardo!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容