class LNode:
"""节点的类"""
def __init__(self,x):
self.data = x
self.next = None
class MyQueue:
"""用链表实现队列,因为列表尾部出列时间复杂度高,所以一般就是在尾部加个指针self.pEnd实现尾入头出(个人理解)"""
def __init__(self):
self.pHead = None
self.pEnd = None#把这个想象成一个指针,用于尾部入列
#判断列表是否为空
def isEmpty(self):
return not self.pHead
#计算列表的长度
def size(self):
s = 0
p = self.pHead
while p != None:
p = p.next
s += 1
return s
#入队列,把元素压入队尾
def enQueue(self,e):
p = LNode(e)
if self.pHead is None:
self.pHead = self.pEnd =p #这里这么写跟self.pHead = p self.pEnd = p 同价
else:
self.pEnd.next = p
self.pEnd = p
#出队列,把元素从队首弹出
def deQueue(self):
if self.pHead is None:
print("
python用链表实现队列
最新推荐文章于 2023-12-05 14:59:43 发布