1 Star 0 Fork 332

liang_666 / leetcode

forked from doocs / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 3.40 KB
一键复制 编辑 原始数据 按行查看 历史
ylb 提交于 2021-04-21 23:12 . feat: update leetcode problems description

143. 重排链表

English Version

题目描述

给定一个单链表 LL0L1→…→Ln-1Ln ,
将其重新排列后变为: L0LnL1Ln-1L2Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.

示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

解法

先通过快慢指针找到链表中点,将链表划分为左右两部分。之后反转右半部分的链表,然后将左右两个链接依次连接即可。

Python3

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if head is None or head.next is None:
            return
        slow, fast = head, head.next
        # 快慢指针找到链表中点
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
        cur = slow.next
        slow.next = None
        pre = None
        # cur 指向右半部分的链表,反转
        while cur:
            t = cur.next
            cur.next = pre
            pre = cur
            cur = t
        cur = head

        # 将左右链表依次连接
        while pre:
            t1 = cur.next
            cur.next = pre
            cur = t1
            t2 = pre.next
            pre.next = t1
            pre = t2

Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null) {
            return;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode cur = slow.next;
        slow.next = null;
        ListNode pre = null;
        while (cur != null) {
            ListNode t = cur.next;
            cur.next = pre;
            pre = cur;
            cur = t;
        }
        cur = head;
        while (pre != null) {
            ListNode t1 = cur.next;
            cur.next = pre;
            cur = t1;
            ListNode t2 = pre.next;
            pre.next = cur;
            pre = t2;
        }
    }
}

...

Java
1
https://gitee.com/liang0011/leetcode.git
git@gitee.com:liang0011/leetcode.git
liang0011
leetcode
leetcode
main

搜索帮助