我使用自制类 Node 定义了一个类 Queue。我认为它按预期工作,但我不确定代码是否正确。大多数情况下,我担心当队列为空时将 self.first 和 self.last 分配给 p (一个新节点)。我的推理是,由于 p 将是唯一的节点,因此它将既是第一个节点也是最后一个节点,但这可能不是 Pythonic 的思维方式。我的下面的代码合理吗?
class Node:
def __init__(self):
self.value=0
self.next=None
class Queue:
def __init__(self):
self.first=None
self.last=None
def isempty(self):
return self.first==None
def put(self,x):
p=Node()
p.value=x
if self.first==None:
self.first=p
self.last=p
else:
self.last.next=p
self.last=p
def get(self):
if self.isempty():
print('Queue is empty!')
else:
x=self.first.value
self.first=self.first.next
return x
最佳答案
这里有一个问题,在第一次调用 get 后你会丢失 Head 指针,还是故意的?
def get(self):
try:
x=self.first.value
self.first=self.first.next
return x
except AttributeError:
print('Empty queue!')
此外,为什么不使用 self.isempty() 方法而不是捕获 AttributeError 呢?
关于 self.last:看来你根本不需要它。
我将修改 Node 如下:
class Node:
def __init__(self, val=0):
self.value= val
self.next = None
这样你就可以写:
def put(self,x):
p = Node(x)
下面可以稍微缩短一下: 来自:
if self.first==None:
self.first=p
self.last=p
else:
self.last.next=p
self.last=p
致:
if self.first==None:
self.first=p
else:
self.last.next=p
self.last=p
使用链表作为队列对我来说有点奇怪,但是嘿,为什么不呢:)
关于代码样式的注意事项: 使用更多空格,并尝试关注https://www.python.org/dev/peps/pep-0008/ 您可以在代码上运行 flake8 或 pylint,通过实践来学习(而不是阅读 PEP ;-) )
编辑:
新的得到很好。您可以像这样避免 else
。根据经验,条件语句/范围越少越好:
if self.isempty():
print('Queue is empty!')
return None
x = self.first.value
self.first = self.first.next
return x
对于您关于 val=0
的问题,它被称为默认参数,因此如果您调用 Node()
而不指定 val
它无论如何都会是0
。
n = Node()
print(n.val)
>> 0
n = Node(42)
print(n.val)
>> 42
关于python - 链接队列类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36016772/