【问题标题】:How can I write my own Python equivalent of stack push and pop functions without using a stack or queue?如何在不使用堆栈或队列的情况下编写自己的 Python 等效堆栈推送和弹出函数?
【发布时间】:2015-04-02 22:46:12
【问题描述】:

我正在使用 Linux 和 Python。我不想使用 os.system 来完成这项工作,也不想使用内置的堆栈或队列函数。

【问题讨论】:

  • 这不是代码编写服务;你尝试过什么,它到底有什么问题?
  • 我正在尝试更多地了解 Python 的工作原理。我很擅长 Bash。我只想编写自己的堆栈推送和弹出。我能否获得足够的帮助来满足我不使用 os.system 或现有 push/pop 命令的要求?
  • 你知道堆栈的工作原理吗?您是否查看过Python's data structures 以寻找可以以类似方式使用的东西?您是什么意思“现有的推送/弹出命令” - listpop,但不是 Queue,这可以接受吗?

标签: python linux stack queue


【解决方案1】:

您可以将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()

【讨论】:

    猜你喜欢
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    • 2015-06-07
    • 2021-03-17
    • 1970-01-01
    • 2014-04-21
    相关资源
    最近更新 更多