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  
        

 

posted @ 2020-08-09 10:36  风不再来  阅读(96)  评论(0编辑  收藏  举报