新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

python判断链表是否有环的实例代码-创新互联

先看下实例代码:

创新互联建站专注于北流网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供北流营销型网站建设,北流网站制作、北流网页设计、北流网站官网定制、微信小程序服务,打造北流网络公司原创品牌,更为您提供北流网站排名全网营销落地服务。
class Node:
  def __init__(self,value=None):
    self.value = value
    self.next = None

class LinkList:
  def __init__(self,head = None):
    self.head = head

  def get_head_node(self):
    """
    获取头部节点
    """
    return self.head
    
  def append(self,value) :
    """
    从尾部添加元素
    """  
    node = Node(value = value) 
    cursor = self.head 
    if self.head is None:
      self.head = node
    else:  
      while cursor.next is not None:
        cursor = cursor.next
    
 
      cursor.next = node
      if value==4:
        node.next = self.head
  
  def traverse_list(self):
    head = self.get_head_node()
    cursor = head
    while cursor is not None:
      print(cursor.value)
      cursor = cursor.next
    print("traverse_over") 
    
  def hasCycle(self, head):
    """
    :type head: ListNode
    :rtype: bool
    """
    slow=fast=head
    while slow and fast and fast.next:
      slow = slow.next
      fast = fast.next.next
      if slow is fast:
        return True
    return False
  

  
def main():
  l = LinkList()
  l.append(1)
  l.append(2)
  l.append(3)
  l.append(4)
  head = l.get_head_node()
  print(l.hasCycle(head))
  #l.traverse_list()


if __name__ == "__main__":
  main()

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网页题目:python判断链表是否有环的实例代码-创新互联
文章分享:http://www.wjwzjz.com/article/dsodsc.html
在线咨询
服务热线
服务热线:028-86922220
TOP