給定一個(gè)鏈表邦蜜,判斷鏈表中是否有環(huán)甲脏。
為了表示給定鏈表中的環(huán)拓诸,我們使用整數(shù) pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1桑李,則在該鏈表中沒有環(huán)踱蛀。
字典索引法 && 空間復(fù)雜度更低的雙鏈表法
class Solution(object):
def hasCycle(self, head):
cur = set([])
while(head is not None):
if(head in cur):
return True
else:
cur.add(head)
head = head.next
return False
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
slow = fast = head
while(True):
if(slow is None or fast is None):
return False
slow = slow.next
if(fast.next is None):
return False
else:
fast = fast.next
if(fast.next is None):
return False
else:
fast = fast.next
if(fast == slow):
return True
```