美文网首页
143. Reorder List

143. Reorder List

作者: 衣介书生 | 来源:发表于2018-04-07 22:17 被阅读6次

题目分析

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}.
这道题目涉及到快慢指针找中心位置,链表逆序,链表合并。

代码

/**
 * 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.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        fast = slow.next;
        slow.next = null;
        // 翻转后半部分
        // 插入法
        // 哑结点
        ListNode dummy = new ListNode(0);
        ListNode temp = null;
        while(fast != null) {
            temp = dummy.next;
            dummy.next = fast;
            fast = fast.next;  // fast 指针后移
            dummy.next.next = temp;
        }
        // 合并
        ListNode temp1 = head;
        ListNode temp2 = head.next;
        temp = dummy.next;
        while(temp != null && temp2 != null) {
            temp1.next = temp;
            temp = temp.next;
            temp1.next.next = temp2;
            temp1 = temp1.next.next;
            temp2 = temp2.next;
        }
        temp1.next = temp;
    }
}

相关文章

  • 143. Reorder List

    题目143. Reorder List Given a singly linked list L: L0→L1→…...

  • 143. Reorder List

    实在是太困了 看不下去这一题的指针,明早上看

  • 143. Reorder List

    题目分析 Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorde...

  • 143. Reorder List

    题目 Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder ...

  • 143. Reorder List

    分为以下几个步骤,1使用快慢指针找到中间节点,2翻转后半部分,3逐个插入节点。

  • 143. Reorder List

    Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it ...

  • 143. Reorder List

    题目描述:给链表如L: L0→L1→…→Ln-1→Ln,将其重新排序为L0→Ln→L1→Ln-1→L2→Ln-2→...

  • 143. Reorder List

    这题很简单,不过很容易出bug特别在merge的时候,所以一定要逻辑清楚,先写好框架

  • 143. Reorder List

    Example 1: Given 1->2->3->4, reorder it to 1->4->2->3.Exa...

  • 143. Reorder List

    重排链表L0 → L1 → … → Ln - 1 → Ln重写为L0 → Ln → L1 → Ln - 1 → L...

网友评论

      本文标题:143. Reorder List

      本文链接:https://www.haomeiwen.com/subject/mijzqftx.html