LeetCode 141题
方法1:快慢指针法
方法2:哈希表法
完整程序
"""
力扣题 :141 环形链表
https://leetcode.cn/problems/linked-list-cycle/
解题思路:
1、哈希表法
2、快慢指针法
首节点附上两个指针,第一个指针每次只遍历一个节点,
第二个指针每次遍历两个节点,直到这两个指针所指的节点相同时,则说明有环。
2022.5.10
"""
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
class Solution:
"判断链表是否为空"
def isEmpty(self,header):
if header.next is None:
return True
def Show(self,header): #显示链表
cur = header
if self.isEmpty(header):
print('空链表')
return
while cur:
if cur.next is not None:
print(cur.val,end='->')
else:
print(cur.val)
cur = cur.next
def hasCycle(self,header):
"""
判断链表是否有环,快慢指针法
:param header:
:return:
"""
if header is None or header.next is None:
return False
slow = header
fast = header.next
while slow != fast:
if fast is None or fast.next is None:
return False
slow = slow.next
fast = fast.next.next
return True
def hasCycle2(self,header):#哈希表法
seen = set()
while header:
if header in seen:
return True
seen.add(header)
header = header.next
return False
# 创建单链表
List = [3,2,0,-4]
header = ListNode(None)
cur = header
for i in range(0,len(List)):
newNode = ListNode(List[i])
cur.next = newNode
cur = cur.next
Solution().Show(header)
# 添加一个指针 构成带环的链表
temp = header.next
pos = 1
count = 0
while count != pos:
temp = temp.next
count += 1
cur.next = temp
print(Solution().hasCycle(header.next))