leetcode-4.19[143. 重排链表、141. 环形链表、142. 环形链表 II](python解法)

题目1

在这里插入图片描述

题解1

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if not head: return None
        p = head
        stack = []
        # 把所有节点压入栈中
        while p:
            stack.append(p)
            p = p.next
        # 长度
        n = len(stack)
        # 找到中点前一个位置 
        mid_num = (n - 1) // 2
        p = head
        while mid_num:
            # 弹出栈顶
            tmp = stack.pop()
            # 与链头拼接(带头结点)
            tmp.next = p.next
            p.next  = tmp
            # 移动一个位置
            p = tmp.next
            mid_num -= 1
        # 将最后一个节点的next赋None
        stack.pop().next = None

题目2

在这里插入图片描述

题解2

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if head is None:
            return False
        fast = slow = head
        # 快慢指针法,时间复杂度O(n)
        while slow and fast.next:
            slow = slow.next
            fast = fast.next.next
            if fast is None or slow is None:
                return False
            if fast == slow:
                return True

题目3

在这里插入图片描述

题解3

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        if head is None:
            return None
        slow = fast = head 
        pointer = head
        while slow and fast.next:
            slow = slow.next
            fast = fast.next.next
            if fast is None or slow is None:
                return None
            if fast == slow:
                break
        else:
            return None
            
        while head != slow:
            head = head.next
            slow = slow.next
        return head

附上题目链接:

题目1链接
题目2链接
题目3链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值