代码
class Node:
def __init__(self, data, _next=None):
self.data = data
self.next = _next
class Queue:
def __init__(self):
self.head = None
self.rear = None
self._length = 0
def is_empty(self):
return self._length == 0
def length(self):
return self._length
def push(self, item):
node = Node(item)
if self.is_empty():
self.head = node
self.rear = node
else:
self.rear.next = node
self.rear = node
self._length += 1
def pop(self):
if self.is_empty():
raise ValueError("队列为空")
value = self.head.data
self.head = self.head.next
self._length -= 1
return value
def peek(self):
if self.is_empty():
raise ValueError("队列为空")
return self.head.data
if __name__ == "__main__":
queue = Queue()
queue.push(1)
queue.push(2)
queue.push(3)
queue.push(4)
print(queue.length())
print(queue.peek())
print(queue.pop())
print(queue.pop())
print(queue.pop())
print(queue.pop())
结果