【问题标题】:Python implementing abstract stackPython实现抽象栈
【发布时间】:2020-01-12 00:30:15
【问题描述】:

我试图在不使用 Python 的内置堆栈/队列方法来理解逻辑的情况下实现堆栈。有人可以解决下面的错误并提供一个可行的解决方案 - 我想我已经接近了。

data = ("a","b","c","d","e","f","g")

stackArray = []
stackPointer = 0
stackMaximum = 7

#Routine to Push
if stackPointer < stackMaximum:
    stackPointer = stackPointer + 1
    stackArray[stackPointer] = data
else:
    print("Stack Full")

#Routine to pop
if stackPointer > 0:
    stackPointer = stackPointer - 1
    stackArray[stackPointer] = data
else:
    print("No data to pop off")

stackArray[stackPointer] = 数据 NameError: 名称“数据”未定义

【问题讨论】:

  • 期望 data来自哪里?
  • 变量名错误。现已更正。
  • 那么你还会遇到同样的错误吗?

标签: python data-structures stack python-3.6


【解决方案1】:
class stack(object):
    def __init__(self, maxsize = None):
     self.stackArrayList = []  #You can use list to implement the stack
     self.maxsize = maxsize

    def isEmpty(self):
     return self.size() == 0 #Checks if the stackArrayList is Empty.

    def push(self, item):
        if len(self.stackArrayList) >= self.maxsize:
            raise Exception("Stack is Full")
        return self.stackArrayList.append(item)  #Append new element to the stackArrayList.

    def pop(self):
        if self.isEmpty():
            raise Exception("Stack empty!")
        return self.stackArrayList.pop()#Pop and return the top element of the stackArrayList.

    def peek(self):
        if self.isEmpty():
            raise Exception("Stack empty!")
        return self.stackArrayList[-1]  #Returns the value of top element in the stackArrayList

    def size(self):
        return len(self.stackArrayList)  #Returns the size of stackArrayList

    def show(self):
        return self.stackArrayList #Returns the contents of the stackArrayList


if __name__ == "__main__":
    # Please note that your input is a tuple
    data = ("a","b","c","d","e","f","g")
    stackArray = stack(maxsize = 7)
    for var in data:
        stackArray.push(var)
    print(stackArray.pop())
    print(stackArray.show())

【讨论】:

    【解决方案2】:

    data 的类型为 tuple。当你将它分配给 stackArray 时,它会给你IndexError: list assignment index out of range

    请参阅https://www.geeksforgeeks.org/stack-data-structure-introduction-program/ 并选择您的语言作为 Python 了解更多详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      相关资源
      最近更新 更多