首页 > 编程语言 > 详细

判断单向列表是否包括环,若包含,环入口的节点计算 python实现

时间:2017-11-04 22:47:25      阅读:287      评论:0      收藏:0      [点我收藏+]
 1 class Node():
 2     def __init__(self,item=None):
 3         self.item = item
 4         self.next = None
 5 
 6 # def doseLinklistContainsLoop(head):
 7 #     if head == None:
 8 #         print("是空的链表")
 9 #         return False
10 #     slowPtr = head
11 #     fastPtr = head
12 #     while fastPtr.next!=None and fastPtr.next.next!=None:
13 #         slowPtr = slowPtr.next
14 #         fastPtr = fastPtr.next.next
15 #         if slowPtr == fastPtr:
16 #             print("是环结构的链表")
17 #             return True
18 #     print("不是环结构的链表")
19 #     return False
20 
21 def findbeginofloop(head):
22     slowPtr = head
23     fastPtr = head
24     loopExist =False
25     if head == None:
26         return False
27     while fastPtr.next != None and fastPtr.next.next != None:
28         slowPtr = slowPtr.next
29         fastPtr = fastPtr.next.next
30         if slowPtr == fastPtr :
31             loopExist = True
32             print("存在环结构")
33             break
34 
35     if loopExist == True:
36         slowPtr  = head
37         while slowPtr != fastPtr:
38             fastPtr = fastPtr.next
39             slowPtr = slowPtr.next
40         return slowPtr
41 
42     print("不是环结构")
43     return False
44 
45 if __name__ == "__main__":
46     node1 = Node(1)
47     node2 = Node(2)
48     node3 = Node(3)
49     node4 = Node(4)
50     node5 = Node(5)
51     node1.next = node2
52     node2.next = node3
53     node3.next = node4
54     node4.next = node5
55     node5.next = node2
56     print(findbeginofloop(node1).item)

 

判断单向列表是否包括环,若包含,环入口的节点计算 python实现

原文:http://www.cnblogs.com/kunpengv5/p/7784791.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!