我正在使用 Linux 和 Python。我不想使用 os.system 来完成此操作,也不想使用内置堆栈或队列函数。
最佳答案
您可以使用列表
作为队列和堆栈:
堆栈:(FILO)
>>> st = list()
>>> st.append(1)
>>> st
[1]
>>> st.append(2)
>>> st
[1, 2]
>>> st.pop() # it removes the last element (i.e. the newest element in the list)
2
>>> st
[1]
队列: (FIFO) - 弹出列表中的第一个元素
>>> que = list()
>>> que.append(1)
>>> que
[1]
>>> que.append(2)
>>> que
[1, 2]
>>> que.pop(0) # we pass in index 0 to remove the earliest element in the list
1
>>> que
[2]
请注意 pop(0)
的性能很差,因为 list()
不是为将其用作队列而设计的。首选使用内置的 collections.deque()
关于python - 如何在不使用堆栈或队列的情况下编写自己的 Python 堆栈推送和弹出函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28303993/