如何解决单链表转循环验证
我是数据结构的新手。在学习循环链表时,我无法继续前进,因为我被卡住了,我正在尝试将单链表转换为循环链表,然后对其进行验证。我的程序没有给出输出,请任何人帮助我。
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Cll:
def __init__(self):
self.head = None
def push(self,data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def makeCircular(self):
temp = self.head
while(temp.next != None):
temp= temp.next
temp.next = self.head
def isCircular(self):
temp = self.head
while (temp.next != None):
temp = temp.next
if temp.next == self.head:
return True
else:
return False
def printList(self):
temp = self.head
#print(temp.data)
while(temp!= None):
print(temp.data,end = " ")
temp = temp.next
print("\n")
cll = Cll()
# l
for i in range(5):
cll.push(i)
cll.printList()
cll.makeCircular()
print(cll.isCircular())
解决方法
您的 isCircular()
方法被破坏,因为如果它是循环的,那么 temp.next != None
将始终为 True
,并且会发生无限循环。
也许可以试试这样的:
def isCircular(self):
temp = self.head
while temp.next is not None and temp.next is not self.head:
temp = temp.next
return temp.next is self.head
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。