美文网首页
143. Reorder List

143. Reorder List

作者: lqsss | 来源:发表于2018-01-12 00:41 被阅读0次

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}.

思路

快慢指针切割两端链表,将后面的链表反转插入到前面的链表

反转列表

遍历head,将head.next节点插入到最前面

需要一个headPtr指向起始节点,每次将head插入到起始节点,就需要重新指向head,而又需要遍历下一个节点,则用next记录下下一个要遍历的节点,让head重新指向它。

合并列表

代码

package linkList;

/**
 * Created by liqiushi on 2018/1/11.
 */
public class ReorderList {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null)
            return null;

        ListNode slow = head;
        ListNode fast = head;
        // 找到中间结点  
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        ListNode second = slow.next;
        slow.next = null;
        second = reverseList(second);

        ListNode first = head;
        // 把第二个链表插在第一个链表中  
        ListNode fptr = null;
        ListNode sptr = null;
        while (second != null) {
            fptr = first.next;
            sptr = second.next;
            first.next = second;
            second.next = fptr;
            first = fptr;
            second = sptr;
        }
    }

    public ListNode reverseList(ListNode head) {
        ListNode headPtr = null;
        ListNode next = null;
        while (head != null) {
            next = head.next;
            head.next = headPtr;
            headPtr = head;
            head = next;
        }
        return headPtr;
    }
}

相关文章

  • 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/fidxoxtx.html