行业知识
数据结构小记【Python/C++版】——栈篇
2026-11-25 22:47:43
来源:互联网转载
一,基础概念
���是一种存放数据的线性结构容器,栈中的数据元素只能在同一端进行添加和删除等操作。
栈中被用来进行数据读写的一端被称作栈顶,无法进行任何操作的另一端被称为栈底。
元素在栈中的移动顺序依照后进先出(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 dequestack = 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 LifoQueuestack = 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.capacityif __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 stackRemoving 1 from the stackInserting 3 into the stack…Inserting 4 into the stack…Top element is 4The stack size is 2Removing 4 from the stackThe stack is not empty
2.C++语言实现
方式1.基于STL标准库自带的std::stack进行实现
方式2.封装一个Stack类来实现
Demo.01: 基于std::stack实现
#include #include using namespace std;void main(){ stack mystack; mystack.push(0); mystack.push(1); mystack.push(2); //弹出并打印栈顶元素 while (!mystack.empty()) { cout
下一篇:linux下怎么开发服务器?