143. Reorder List

题目

原始地址:https://leetcode.com/problems/reorder-list/#/description

/**
 * 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) {
        
    }
}

描述

给定链表L:l0->l1->...->l(n-1)->ln,
重新排列为:l0->ln->l1->l(n-1)->l2->l(n-2)...

分析

这个题目没有什么奇技淫巧,按部就班来吧。
第一步用快慢指针的方式找到链表中点,把链表分割成左右两部分;
第二步把右半部翻转;
第三步再把两部分合并,或者说是把右半部分的节点逐个插入到左半部分节点之间。

解法

/**
 * 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;
        }
        ListNode l1 = head, l2 = head, next;
        while (l1.next != null && l1.next.next != null) {
            l1 = l1.next.next;
            l2 = l2.next;
        }
        l1 = l2.next;
        l2.next = null;
        l2 = null;
        while (l1 != null) {
            next = l1.next;
            l1.next = l2;
            l2 = l1;
            l1 = next;
        }
        l1 = head;
        while (l2 != null) {
            next = l1.next;
            l1.next = l2;
            l2 = l2.next;
            l1.next.next = next;
            l1 = next;
        }
    }
}
posted @ 2017-05-06 14:28  北冥尝有鱼  阅读(87)  评论(0编辑  收藏  举报