Reorder List(重排链表)

问题

Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln

reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

Have you met this question in a real interview? Yes
Example
Given 1->2->3->4->null, reorder it to 1->4->2->3->null.

分析

因为链表没有角标,操作时必须从前向后,而题目的要求又是Ln在前边,所以我们考虑先找到中间的节点,然后把后半部分进行翻转,然后再和前半部分进行合并即可。

代码

/**
 * Definition for ListNode.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int val) {
 * this.val = val;
 * this.next = null;
 * }
 * }
 */
public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: void
     */
    public void reorderList(ListNode head) {
        // write your code here
        if (head == null) {
            return;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (true) {
            if (fast == null || fast.next == null) {
                break;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode node = slow.next;
        slow.next = null;
        slow = node;
        while (slow != null) {
            ListNode temp = slow.next;
            if (temp == null) {
                break;
            }
            slow.next = temp.next;
            temp.next = node;
            node = temp;
        }
        ListNode temp = new ListNode(0);
        boolean b = true;
        while (head != null && node != null) {
            if (b) {
                temp.next = head;
                head = head.next;
            } else {
                temp.next = node;
                node = node.next;
            }
            temp = temp.next;
            b = !b;
        }
        if (head != null) {
            temp.next = head;
            temp = temp.next;
        }
        if (node != null) {
            temp.next = node;
        }
    }
}

你可能感兴趣的:(Reorder List(重排链表))