Python语言基础
Python语言进阶
Python数据结构

Python 堆栈

Python 堆栈详细操作教程
在英语词典中,单词stack的意思是将对象排列在另一个对象上。这与在此数据结构中分配内存的方式相同。它以与将一堆盘子在厨房中一个接一个地存储的方式相似的方式存储数据元素。因此,堆栈数据结构允许在一端的操作可称为堆栈顶部。我们只能在堆栈中添加或删除元素。
在堆栈中,按顺序最后插入的元素将首先出现,因为我们只能从堆栈顶部移除。这种功能称为后进先出(LIFO)功能。添加和删​​除元素的操作称为PUSH和POP。在以下程序中,我们将其实现为添加和删除功能。我们声明一个空列表,并使用append()和pop()方法添加和删除数据元素。

压入堆栈

# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
class Stack:
    def __init__(self):
        self.stack = []
    def add(self, dataval):
# Use list append method to add element
        if dataval not in self.stack:
            self.stack.append(dataval)
            return True
        else:
            return False
# Use peek to look at the top of the stack
    def peek(self):
return self.stack[-1]
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
print(AStack.peek())
执行以上代码后,将产生以下结果:
Tue
Thu

堆栈中的POP

众所周知,我们只能从堆栈中删除最上面的数据元素,因此我们实现了一个python程序。以下程序中的remove函数返回最上面的元素。我们首先通过计算堆栈的大小来检查顶部元素,然后使用内置的pop()方法找出顶部元素。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
class Stack:
    def __init__(self):
        self.stack = []
    def add(self, dataval):
# Use list append method to add element
        if dataval not in self.stack:
            self.stack.append(dataval)
            return True
        else:
            return False
# Use list pop method to remove element
    def remove(self):
        if len(self.stack) <= 0:
            return ("No element in the Stack")
        else:
            return self.stack.pop()
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())
执行以上代码后,将产生以下结果:
Thu
Wed
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4