zoukankan      html  css  js  c++  java
  • 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  
            
  • 相关阅读:
    蓝桥网试题 java 基础练习 特殊的数字
    蓝桥网试题 java 基础练习 杨辉三角形
    蓝桥网试题 java 基础练习 查找整数
    蓝桥网试题 java 基础练习 数列特征
    蓝桥网试题 java 基础练习 字母图形
    蓝桥网试题 java 基础练习 01字串
    蓝桥网试题 java 基础练习 回文数
    蓝桥网试题 java 基础练习 特殊回文数
    Using text search in Web page with Sikuli
    each of which 用法
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13461862.html
Copyright © 2011-2022 走看看