[英]How can I write my own Python equivalent of stack push and pop functions without using a stack or queue?
我正在使用Linux和Python。 我既不想使用os.system来完成此任务,也不想使用内置的堆栈或队列函数。
您可以将list
用于队列和堆栈:
堆栈: (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()
是首选
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.