Python程序检测链表中的循环

王林
发布: 2023-09-06 17:05:08
转载
1389人浏览过

当链表中的任何节点不指向 null 时,就称链表存在循环。最后一个节点将指向链表中的前一个节点,从而创建一个循环。有环的链表不会有终点。

在下面的示例中,最后一个节点(节点 5)未指向 NULL。相反,它指向节点 3,并建立了一个循环。因此,上面的链表是没有尽头的。

Python程序检测链表中的循环

算法快速和慢速获取两个指针

  • 两个指针最初都会指向链表的 HEAD。

  • 慢速指针总是加一,快指针总是加二。

  • 在任何时候,如果快指针和慢指针都指向同一个节点,则称链表存在环。

    立即学习Python免费学习笔记(深入)”;

考虑下面的链表示例,其中最后一个节点指向第二个节点 -

示例

慢指针和快指针都指向同一个节点。因此,可以得出结论,给定的链表包含一个循环。

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None


class LinkedList:
    def __init__(self):
        self.head = None

    def insert_at_the_end(self,newVal):
        newNode=Node(newVal)
        if self.head==None:
            self.head=newNode
            return
        temp=self.head
        while(temp.next):
            temp=temp.next
        temp.next=newNode


    def Print_the_LL(self):
        temp = self.head
        if(temp != None):
          print("\nThe linked list elements are:", end=" ")
          while (temp != None):
            print(temp.val, end=" ")
            temp = temp.next
        else:
          print("The list is empty.")
    def detect_loop(self):
        slow=self.head
        fast=self.head
        while(fast):
            if slow==fast:
                print("\nA loop has been detected in the linked list ")
                return
            slow=slow.next
            fast=fast.next


newList = LinkedList()
newList.insert_at_the_end(1)
newList.insert_at_the_end(2)
newList.insert_at_the_end(3)
newList.insert_at_the_end(4)
newList.Print_the_LL()
print("\n")
newList.head.next.next.next.next=newList.head.next
newList.detect_loop()
登录后复制

输出

在链表中检测到了一个循环。

The linked list elements are: 1 2 3 4 

A loop has been detected in the linked list
登录后复制

以上就是Python程序检测链表中的循环的详细内容,更多请关注php中文网其它相关文章!

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号