有关链表的LeetCode做题笔记合集,Python实现
链表定义
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
141. 环形链表 Linked List Cycle
三种方法
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