专业编程基础技术教程

网站首页 > 基础教程 正文

Python|用一个列表自定义一个栈类

ccvgpt 2024-08-07 18:44:38 基础教程 8 ℃

栈的特点在于以后进先出的方式存取数据(不是随机存取)。

栈最典型的应用是用于函数调用。当调用一个函数时,一个存储这个函数的参数和局部问题的活动记录被压入栈中。当一个函数调用另一个函数时,这个新函数的活动记录被压入栈。当一个函数结束它的工作返回它的调用者时,它的活动记录从栈中删除。

Python|用一个列表自定义一个栈类

在Python的标准库中已经实现了栈的模块化:

from Stack import Stack

stack = Stack()

for i in range(10):

....stack.push(i)

stack.pop()

while not stack.isEmpty():

....print(stack.pop(), end = " ")

output:

8 7 6 5 4 3 2 1 0

可以自定义一个类来对堆栈建模,并且使用列表来存储栈中的元素。栈类可以继承list来扩展(但也会继承不一些不需要的方法),也可以在一个自定义的Stack类中创建一个列表。

代码说明:

__elements.pop()是列表的pop()方法;

stack.pop()是自定义栈类对象stack的pop()方法;

所以如果用继承list类的思路,此方法不需重写即可使用。

output:

8 7 6 5 4 3 2 1 0

附代码:

class Stack:

....def __init__(self):

........self.__elements = []

............................# Return true if the tack is empty

....def isEmpty(self):

........return len(self.__elements) == 0

............................# Returns the element at the top of the stack

............................# without removing it from the stack.

....def peek(self):

........if self.isEmpty():

............return None

........else:

............return self.__elements[len(elements) - 1]

............................# Stores an element into the top of the stack

....def push(self, value):

........self.__elements.append(value)

....................# Removes the element at the top of the stack and returns it

....def pop(self):

........if self.isEmpty():

............return None

........else:

............return self.__elements.pop()

............................# Return the size of the stack

....def getSize(self):

........return len(self.__elements)

stack = Stack()

for i in range(10):

....stack.push(i)

stack.pop()

while not stack.isEmpty():

....print(stack.pop(), end = " ")

-End-

Tags:

最近发表
标签列表