Python实现抽象

2024-05-15 12:44:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在不使用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:未定义名称“数据”


Tags: to数据方法dataif队列堆栈pop
2条回答
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())

data属于tuple类型。当您将其分配给stackArray时,它将给您IndexError: list assignment index out of range

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

相关问题 更多 >