1. 程式人生 > 實用技巧 >102. 帶環連結串列

102. 帶環連結串列

102.帶環連結串列

中文English

給定一個連結串列,判斷它是否有環。

樣例

```
樣例 1:
	輸入: 21->10->4->5,  then tail connects to node index 1(value 10).
	輸出: true
	
樣例 2:
	輸入: 21->10->4->5->null
	輸出: false

```

挑戰

不要使用額外的空間

輸入測試資料(每行一個引數)如何理解測試資料?

快慢指標解法:

如果是帶環的,快慢指標最終會相等,則直接返回True,否則False,走到Null

"""
Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of linked list. @return: True if it has a cycle, or false """ def hasCycle(self, head): # write your code here #快慢指標,如果最終相等,則是帶環
if not head: return False slowPtr,fastPtr = head, head #如果fasePtr有值的話,那麼slowPtr一定也有值,所以如果要判斷fastPtr.next.next是否有值,fastPtr.next必須需要先判斷 while fastPtr.next and fastPtr.next.next: slowPtr = slowPtr.next fastPtr = fastPtr.next.next #如果最終相等
if slowPtr == fastPtr: return True return False

set()解法,儲存當前節點的地址,id(head),如果是已經訪問過,則返回True

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: The first node of linked list.
    @return: True if it has a cycle, or false
    """
    def hasCycle(self, head):
        # write your code here
        #set儲存,訪問過的節點id(head),如果已經訪問過,則返回True,否則False,根據head的地址來進行儲存
        
        if not head: return False
        
        array = set()
        while head:
            if (id(head) in array):
                return True 
            else:
                array.add(id(head))
            head = head.next
        
        return False