gpt4 book ai didi

python - 不使用堆栈的反向队列

转载 作者:太空宇宙 更新时间:2023-11-03 21:10:32 25 4
gpt4 key购买 nike

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

def __str__(self):
return "Node({})".format(self.value)

__repr__ = __str__

class Queue:
def __init__(self):
self.head=None
self.tail=None

def __str__(self):
temp=self.head
out=[]
while temp:
out.append(str(temp.value))
temp=temp.next
out=' '.join(out)
return ('Head:{}\nTail:{}\nQueue:{}'.format(self.head,self.tail,out))

__repr__=__str__

def isEmpty(self):
#write your code here
return (self.head == None) and (self.tail == None)
def __len__(self):
#write your code here
current = self.head
len = 0
while current:
len += 1
current = self.head.next
if self.head.next == self.tail:
break
return len

def enqueue(self, value):
#write your code here
node = Node(value)
if self.isEmpty():
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node

def dequeue(self):
#write your code here
if self.isEmpty():
return 'Queue is empty'
else:
popped = self.head.value
self.head = self.head.next
return popped

def front(self):
if self.head != None:

return self.head.value

q = Queue()
def reversequeue(q):
if q.isEmpty() == False:
data = q.front()
q.dequeue()
reversequeue(q)
q.enqueue(data)
def QueuePalindrome(word):
q = Queue()
for i in word:
q.enqueue(i)

p = reversequeue(q)
return p

函数reversequeue返回“Nonetype”对象没有属性值。我不知道如何继续。

当我测试 q.front() 时。它返回正确的答案。我尝试通过指出如果 self.head == None 则跳过它来捕获错误。

遇到这种情况我该怎么办?

请帮忙。非常感谢!

最佳答案

您的函数reversequeue(q)没有return语句

def reversequeue(q):
if q.isEmpty() == False:
data = q.front()
q.dequeue()
reversequeue(q)
q.enqueue(data)

因此它默认返回None。只需为基本情况和递归情况添加返回,然后更新 q:

def reversequeue(q):
if q.isEmpty() == False:
data = q.front()
q.dequeue()
q = reversequeue(q)
q.enqueue(data)
return q
return Queue()

关于python - 不使用堆栈的反向队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55095251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com