数据结构: 栈

博客介绍了栈的基本概念,栈是只允许在一端操作的线性表,具有后进先出特性,常见操作有创建、销毁、入栈、出栈等。实现栈可采用数组和链表作为存储结构,操作时需判断栈满或栈空等情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本概念

是一种只允许在一端进行操作的线性表。具体地说,栈是一种特殊的线性表,只允许在栈顶进行操作,而栈底不允许操作。

由于仅容许在一端操作,使其具有后进先出的结构特性。

常见的栈操作包括:
创建栈、销毁栈、清空栈、入栈、出栈、获取栈顶元素、获取栈的大小等。例如,在C++中,对栈的介绍如下:

std::stack

template <class T, class Container = deque<T> > class stack;

LIFO stack Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container.

stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.

The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall support the following operations:
empty size back push_back pop_back

The standard container classes vector, deque and list fulfill these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container deque is used.

在这里插入图片描述

简单示例
#include <stack>
#include <iostream>
using namespace std;
int main()
{
	stack<int> test_stack;
	cout << test_stack.empty() << endl;
	cout << test_stack.size() << endl;

	for (size_t i = 0; i < 5; ++i)
	{
		test_stack.push(i);

	}

	cout << test_stack.top() << endl;
	test_stack.pop();
	cout << test_stack.top() << endl;
	
	return 0;
}

实现

实现栈时,可以采用数组链表作为栈的存储结构。

我们需要:
保存当前栈顶位置栈顶标识;
栈的最大容量及存储空间;
栈当前大小。

入栈时判断栈是否满;
出栈时判断栈是否为空;
获取栈顶元素时判断栈是否为空;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值