数据结构小记【Python/C++版】——栈篇
一,基础概念
栈是一种存放数据的线性结构容器,栈中的数据元素只能在同一端进行添加和删除等操作。
栈中被用来进行数据读写的一端被称作栈顶,无法进行任何操作的另一端被称为栈底。
元素在栈中的移动顺序依照后进先出(LIFO)原则,较早入栈的元素,更接近栈底,更晚被弹出。
栈结构在生活中的抽象模型有:酒店堆起来的盘子,书架上堆起来的书等,都是从最顶部开始取走和放回的。
二,栈的图示结构
三,栈的常见操作
push: 入栈操作,将数据从栈顶压入。
pop: 出栈操作,从栈顶弹出数据。
peek: 返回栈顶的数据而不删除它。
size: 返回栈中数据的数量。
isEmpty: 检查栈是否为空。
isFull: 检查栈是否已满。
四,栈的代码实现
1.Python语言实现
方式1.使用Python内置数据类型实现:
list, collections.deque, queue.LifoQueue
方式2.封装Stack类来实现
Demo.01: 基于list实现
stack = []
#基于append函数实现入栈操作
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack:')
print(stack)
print('\nElements popped from stack:')
#基于pop函数实现出栈操作
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
Demo.02: 基于deque实现
from collections import deque
stack = deque()
#基于append函数实现入栈操作
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack:')
print(stack)
print('\nElements popped from stack:')
#基于pop函数实现出栈操作
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
Demo.03: 基于LifoQueue实现
from queue import LifoQueue
stack = LifoQueue(maxsize=3)
print(stack.qsize())
#基于put函数实现入栈操作
stack.put('a')
stack.put('b')
stack.put('c')
print("Full: ", stack.full())
print("Size: ", stack.qsize())
#基于get函数实现出栈操作
print('\nElements popped from the stack')
print(stack.get())
print(stack.get())
print("\nEmpty: ", stack.empty())
Demo.04: 封装Stack类来实现
class Stack:
#初始化栈
def __init__(self, size):
self.arr = [None] * size
self.capacity = size
self.top = -1
#入栈操作
def push(self, val):
if self.isFull():
print('Stack is full…')
exit(-1)
print(f'Inserting {val} into the stack…')
self.top = self.top + 1
self.arr[self.top] = val
#出栈操作
def pop(self):
if self.isEmpty():
print('Stack is empty..')
exit(-1)
print(f'Removing {self.peek()} from the stack')
top = self.arr[self.top]
self.top = self.top - 1
return top
#返回栈顶元素
def peek(self):
if self.isEmpty():
exit(-1)
return self.arr[self.top]
def size(self):
return self.top + 1
def isEmpty(self):
return self.size() == 0
def isFull(self):
return self.size() == self.capacity
if __name__ == '__main__':
stack = Stack(3)
stack.push(1)
stack.push(2)
stack.pop()
stack.pop()
stack.push(3)
stack.push(4)
print('Top element is', stack.peek())
print('The stack size is', stack.size())
stack.pop()
if stack.isEmpty():
print('The stack is empty')
else:
print('The stack is not empty')
运行结果:
Inserting 1 into the stack…
Inserting 2 into the stack…
Removing 2 from the stack
Removing 1 from the stack
Inserting 3 into the stack…
Inserting 4 into the stack…
Top element is 4
The stack size is 2
Removing 4 from the stack
The stack is not empty
2.C++语言实现
方式1.基于STL标准库自带的std::stack进行实现
方式2.封装一个Stack类来实现
Demo.01: 基于std::stack实现
#include <iostream>
#include <stack>
using namespace std;
void main()
{
stack<int> mystack;
mystack.push(0);
mystack.push(1);
mystack.push(2);
//弹出并打印栈顶元素
while (!mystack.empty()) {
cout << ' ' << mystack.top();
mystack.pop();
}}
Demo.02: 封装Stack类来实现
#include<iostream>
using namespace std;
#define MAX 1024
class Stack
{
int top;
public:
int myStack[MAX];
Stack() { top = -1; }
bool push(int x);
int pop();
bool isEmpty();
};
bool Stack::push(int item)
{
if (top >= (MAX - 1)) {
cout << "stack is full..";
return false;
}
else {
myStack[++top] = item;
cout << item << endl;
return true;
}
}
int Stack::pop()
{
if (top < 0) {
cout << "stack is empty..";
return 0;
}
else {
int item = myStack[top--];
return item;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
int main()
{
class Stack stack;
cout << "The Stack Push " << endl;
stack.push(2);
stack.push(4);
stack.push(6);
cout << "The Stack Pop : " << endl;
while (!stack.isEmpty())
{
cout << stack.pop() << endl;
}
return 0;
}
运行结果:
The Stack Push
2
4
6
The Stack Pop :
6
4
2
五,栈的应用场景
栈在软件开发中的主要应用场景有:
1.表达式解析,对表达式的前缀/后缀进行出栈/入栈操作来解析表达式的内容。
2.程序运行记录跟踪,比如在Web浏览器中,每访问一个新页面时,URL被添加到栈中,当点击后退按钮时,栈中弹出以前的URL。
3.实现其他更复杂的数据结构,比如树和图。
简单应用案例
1.场景:编写一个算法,从左到右读取字符串中所有的括号字符,判断其中的括号是否都能互相匹配。
2.实现步骤:
step.1:新建一个空的栈。
step.2:从左往右依次读取括号字符,如果遇到左括号,调用push将字符压入堆栈,如果遇到右括号,调用pop弹出栈顶的字符。
step.3:如果存在左括号与右括号不匹配,结束时,栈中数据不为空。如果所有的左括号与右括号匹配,结束时,栈中的数据是空的。
3.Python代码实现:
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.insert(0, item)
def pop(self):
return self.items.pop(0)
def peek(self):
return self.items[0]
def size(self):
return len(self.items)
def parChecker(symbolString):
s = Stack()
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol == "(":
s.push(symbol)
else:
if s.isEmpty():
balanced = False
else:
s.pop()
index = index + 1
if balanced and s.isEmpty():
return True
else:
return False
if __name__ == '__main__':
test_st1 = "((()))"
print("The check result is :", parChecker(test_st1))
test_st2 = "((())"
print("The check result is :", parChecker(test_st2))
运行结果:
The check result is : True
The check result is : False
六,参考阅读
《Problem Solving with Algorithms and Data Structures Using Python, Second Edition》
https://www.geeksforgeeks.org/stack-in-python/
https://www.techiedelight.com/zh/stack-implementation-python/
相关文章
- pycharm打包python项目_Python怎么打包
- aic准则python_Python数据科学:线性回归
- python进制转换函数-Python中进制转换函数的使用
- python常用面试题_Python+Selenium 常见面试题整理[通俗易懂]
- python安装pygame教程_python-pygame安装教程
- 利用Python读取和修改Excel文件(包括xls文件和xlsx文件)——基于xlrd、xlwt和openpyxl模块
- python setattr函数_Python内置函数(53)——setattr
- python表情代码_Python实现表情包的代码实例[通俗易懂]
- 从零开始配置vim(25)——关于 c++ python 的配置
- 运维Python自动化之路:基础信息模块之IPy模块
- Python保存json_python保存json文件
- python抛出异常写法_零基础学 Python(32):如何抛出和捕获异常?「建议收藏」
- python type error是什么意思_Python 报错 TypeError:’DoesNotExist’对象不可调用
- Python爬虫之分布式爬虫
- Python 多分派机制,让你的代码更简洁更灵活
- 数据结构小记【Python/C++版】——链表篇
- 数据结构小记【Python/C++版】——图结构篇
- 自定义Python版本ESL库访问FreeSWITCH
- python实现一个简单的2048游戏详解编程语言
- Python简易操作MySQL数据库指南(python操作mysql数据库)
- Python实现快速连接Redis数据库(python连接redis)
- Python实现Oracle数据库连接(python连接oracle数据库)
- 从 Python 连接到 MySQL:实现更多强大的数据库应用(python和mysql)
- python开发的小球完全弹性碰撞游戏代码
- python操作MongoDB基础知识
- python正则匹配抓取豆瓣电影链接和评论代码分享
- Python中的引用和拷贝浅析