zoukankan      html  css  js  c++  java
  • 【LeetCode】【Python】Linked List Cycle

    Given a linked list, determine if it has a cycle in it.

    Follow up:

    Can you solve it without using extra space?


    思路:笨办法是每一个节点再开辟一个属性存放是否訪问过,这样遍历一遍就可以知道是否有环。但为了不添加额外的空间。能够设置两个指针。一个一次走一步,还有一个一次走两步,假设有环则两个指针一定会再次相遇。反之则不会。


    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    class Solution:
        # @param head, a ListNode
        # @return a boolea
        def hasCycle(self, head):
            if head is None:
                return False
            p1 = head
            p2 = head
            while True:
                if p1.next is not None:
                    p1=p1.next.next
                    p2=p2.next
                    if p1 is None or p2 is None:
                        return False
                    elif p1 == p2:
                        return True
                else:
                    return False
            return False


  • 相关阅读:
    端口查看netstat -tunpl |grep 25
    解释一下查找出文件并删除find /var/log -type f -mtime +7 -ok rm {} ;
    2021.6.2
    2021.6.1
    2021.5.31
    2021.5.30(每周总结)
    2021.5.28
    2021.5.27
    2021.5.26
    2021.5.25
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5216884.html
Copyright © 2011-2022 走看看