python - 如何在不使用堆栈或队列的情况下编写自己的 Python 堆栈推送和弹出函数?

标签 python linux stack queue

我正在使用 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/

相关文章:

在linux下创建一个自由运行的实时定时器

c++ - 为什么不满足我的 "while"条件?

c - 在 PIC16/18 中捕获中断之前是否可以知道 PCL 的值?

python - 选择脚本语言

linux - scanmem (Linux) 与 CheatEngine (Win)

python - 有没有一种简单的方法可以为 Kivy 按钮添加边框

linux - 如何使 xdotool 与 matchbow-window-manager 一起工作?

c++ - 使用 Push、Pop 等在 C++ 中创建堆栈

Python、Linux : How to delete unicode files?

python - 使用正则表达式从字符串中提取首字母缩略词模式