我正在尝试使用具有实现入队,出队和长度功能的链接实现来实现队列类。以我对队列的了解,第一次实现时,队列指向头节点和尾节点,而头节点和尾节点最初指向无。将项目添加到队列时,一个节点指向该项目,头节点保持不变,而尾节点指向新项目。
我已经尝试使用以下代码在python中实现此功能,但是它似乎无法正常工作。我不确定我的逻辑是否错误,或者是编码错误,还是两者都有?
class Queue:
def __init__(self, data=None):
# Initialize this queue, and store data if it exists
self.data = data
self.head = None
self.tail = None
self.node = None
self.length = 0
def enqueue(self, data):
if self.head == None:
self.head = Queue(data)
self.tail = self.head
else:
self.node = data
self.tail = self.node
data = self.data
self.length += 1
def dequeue(self):
item = self.head.item
self.head = self.head.next
self.length -= 1
return item
def __len__(self):
return self.length
我会避免在类的定义内声明类的实例。在我看来,声明self.head = Queue(data)
会带来麻烦,因为这可能导致声明self.head.head
和self.head.head.head
...您明白了。相反,我可能会把事情分开。另外,请注意,即使您在方法中调用了它们,也没有声明self.head.next
或self.head.item
。
也许声明了两个类,一个类用于Nodes,另一个用于由Nodes构建的队列?这样可以简化一些事情。
以下是我在Python中构建队列的方法,请相信我自己的方法:
from typing import Iterable
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __call__(self):
return self.data
class Queue:
def __init__(self, x=None):
assert isinstance(x, Node) or (x == None) or isinstance(x, Iterable)
if isinstance(x, Iterable):
self.head = Node(x[0])
self.tail = Node(x[0])
self.length = 1
self.to_queue(x[1:])
else:
self.head = x
self.tail = x
self.length = 1 if x else 0
def enque(self, data):
tmp = self.head
self.head = Node(data)
self.head.next = tmp
self.length += 1
def deque(self):
if self.length <= 0:
print("empty Queue")
return
tmp = self.head
for i in range(self.length-2):
tmp = tmp.next
self.tail = tmp
self.tail.next = None
self.length -= 1
if self.length == 0:
self.head = None
self.tail = None
def to_queue(self, vals):
for i in vals:
self.enque(i)
def __call__(self):
tmp = self.head
while (tmp):
print(tmp.data, end=" ")
tmp = tmp.next
def __len__(self):
return self.length