题目
描述
请你实现一个队列。
操作:
push x:将 x 加入队尾,保证 x 为 int 型整数。
pop:输出队首,并让队首出队
front:输出队首:队首不出队
输入描述:
第一行为一个正整数 n ,代表操作次数。(1≤n≤100000)
接下来的 n,每行为一个字符串,代表一个操作。保证操作是题目描述中三种中的一种。
输出描述:
如果操作为push,则不输出任何东西。
如果为另外两种,若队列为空,则输出 "error“
否则按对应操作输出。
示例
输入:
6
push 1
pop
front
push 2
push 3
pop
输出:
1
error
2
代码
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(): #head 和rear都指向第一个结点
self.head = node
self.rear = node
else:
self.rear.next = node
self.rear = node
self._length += 1
def pop(self):
# 抛出队首元素 head从指向第一个节点变为指向第二个结点
if self.is_empty():
return "error"
value = self.head.data
self.head = self.head.next
self._length -= 1
return value
def front(self):#输出队首 队首不出队
if self.is_empty():
return "error"
return self.head.data
if __name__ == "__main__":
queue = Queue()
n = int(input())
while n:
n = n - 1
s = input('')# 在pycharm中改为s = input(' ')
a = s.split()[0]
if a == "push":
num = int(s.split()[1])
queue.push(num)
elif a == "pop":
print(queue.pop())
else:
print(queue.front())