LeetCode143. 重排链表

题目

LeetCode143. 重排链表
给定一个单链表 L 的头节点 head ,单链表 L 表示为:

L0 → L1 → … → Ln - 1 → Ln

请将其重新排列后变为:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

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

题解

# 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
        fast, last = head.next, head
        while fast and fast.next:
            fast = fast.next.next
            last = last.next
        # fast = None(长度奇数,待插入节点往后移一个) or last Node(长度偶数),eg:
        # 1 2 3 4 5
        # 1 5 2 4 3
        need_insert, last.next = last.next, None    # 记录待插入的节点,重置后最尾链表置为空

        # 反转待插入链表(头插法)
        tmp = ListNode()
        while need_insert:
            tmp.next, tmp.next.next, need_insert = need_insert, tmp.next, need_insert.next
        tmp = tmp.next  # 将tmp指向反转后的首个节点

        # 依次插入
        while tmp:
            head.next, head.next.next, tmp = tmp, head.next, tmp.next
            head = head.next.next


def print_list(head: ListNode):
    while head:
        print(head.val, end=' ')
        head = head.next
    print()


if __name__ == '__main__':    
    a = ListNode(1, next=ListNode(2, next=ListNode(3, next=ListNode(4, next=ListNode(5)))))
    Solution().reorderList(a)
    print_list(a)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值