我正在尝试仅使用头指针(无尾)构造一个Queue链表。 但我似乎无法排在列表的末尾。
示例:目前代码将:c -> b -> a
,但我想将其反转a -> b -> c
。
class Node:
'''A node for a linked list.'''
def __init__(self, initdata):
self.data = initdata
self.next = None
class Queue(object):
def __init__(self):
self.head = None
def enqueue(self, item):
"""Add an item onto the tail of the queue."""
if self.head == None:
temp = Node(item)
temp.next = self.head
self.head = temp
else:
current = self.head
while current != None:
current = current.next
if current == None:
temp = Node(item)
temp.next = current
current = temp
def dequeue(self):
if self.head == None:
raise IndexError("Can't dequeue from empty queue.")
else:
current_first = self.head
current = self.head.next
return current_first.data
答案 0 :(得分:0)
这应该这样做:
ExistingClass
除了一些逻辑修复(我们需要创建一个新节点并将其存储在class Node:
'''A node for a linked list.'''
def __init__(self, initdata):
self.data = initdata
self.next = None
class Queue(object):
def __init__(self):
self.head = None
def enqueue(self, item):
"""Add an item onto the tail of the queue."""
if self.head is None:
self.head = Node(item)
else:
current = self.head
while current.next is not None:
current = current.next
current.next = Node(item)
def dequeue(self):
if self.head is None:
raise IndexError("Can't dequeue from empty queue.")
else:
first = self.head
self.head = self.head.next
return first.data
中,current.next
只是一个指向节点的变量),请注意我们使用current
运算符测试is
和None
构造函数来设置数据(这样我们就可以创建和分配没有Node
var的新节点。)
例如:
temp
输出:
q = Queue()
q.enqueue('a')
q.enqueue('b')
q.enqueue('c')
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
顺便说一下,请注意,此类结构需要a
b
c
插入时间和O(N)
删除(弹出)时间。双端队列(如标准collections.deque
)将在固定时间内进行插入和删除。