LeetCode 141 环形链表 Linked List Cycle Python

有关链表的LeetCode做题笔记合集,Python实现

链表定义

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

141. 环形链表 Linked List Cycle

LeetCodeCN 第141题链接

三种方法
1.硬做,可以设置超时或者固定循环次数,不靠谱
2.做记号,使用set来储存遍历过的节点,需要额外内存空间
3.快慢指针,慢指针每次前移一个节点,快指针每次前移两个节点,如果链表存在循环那快慢指针肯定会相遇

class Solution(object):
    # 1.硬做
    def hasCycle1(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head:
            return False
        curr = head
        for i in range(100000):
            curr = curr.next
            if not curr:
                return False
        return True
    
    # 2.set记录
    def hasCycle2(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        rec = set()
        curr = head
        while curr:
            if curr in rec:
                return True
            rec.add(curr)
            curr = curr.next
        return False
    
    # 3.快慢指针
    def hasCycle3(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        slow = fast = head
        while slow and fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

下一题:142. 环形链表 II Linked List Cycle II

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值