LeetCode:141. 环形链表(python)
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
进阶:你能用 O(1)(即,常量)内存解决此问题吗?
思路:
- 快慢指针法
- 若为环形链表,则通过迭代,快慢指针将会相交
- 若不为环形链表,则快指针将会遍历至链表的尾端
- 哈希法
附代码(Python3):
-
快慢指针法
class ListNode: def __init__(self, x): self.val = x self.next = None # 快慢双指针 class Solution(object): def hasCycle(self, head): if not head: return None slow, quick = head, head.next # 快慢指针 while slow!=quick: if quick==None or quick.next==None: # 快指针或快指针的next为空,则遍历至链表尾部,非环形链表 return False else: slow = slow.next # 慢指针走一步 quick = quick.next.next # 快指针走两步 return True # 快慢指针相遇,则为环形链表
# 构建环形链表 def bulid_loop_link(nums, pos): res = cur = ListNode(None) meet = False for i in range(len(nums)): cur.next = ListNode(nums[i]) cur = cur.next if i==pos: meet = cur if meet: cur.next = meet return res.next test = Solution() # 示例1 head1 = bulid_loop_link([3,2,0,-4], 1) print(test.hasCycle(head1)) # 示例2 head2 = bulid_loop_link([1,2], 0) print(test.hasCycle(head2)) # 示例3 head3 = bulid_loop_link([1], -1) print(test.hasCycle(head3))
True True False
-
哈希法
class ListNode: def __init__(self, x): self.val = x self.next = None # 哈希法 class Solution(object): def hasCycle(self, head): if not head: return None res = set() # 创建集合 while head: # 遍历链表 if head not in res: # 不在集合,则添加节点 res.add(head) else: # 否则,为环形链表 return True head = head.next return False # 遍历结束,则为非环形链表
# 构建环形链表 def bulid_loop_link(nums, pos): res = cur = ListNode(None) meet = False for i in range(len(nums)): cur.next = ListNode(nums[i]) cur = cur.next if i==pos: meet = cur if meet: cur.next = meet return res.next test = Solution() # 示例1 head1 = bulid_loop_link([3,2,0,-4], 1) print(test.hasCycle(head1)) # 示例2 head2 = bulid_loop_link([1,2], 0) print(test.hasCycle(head2)) # 示例3 head3 = bulid_loop_link([1], -1) print(test.hasCycle(head3))
True True False