STL容器Stack的详细使用方法

STL容器Stack的详细使用方法

  • 栈是一种FILO即先进后出的数据结构,栈内的元素不能访问。如果一定要访问栈内的元素,只能将其上方的元素全部从栈中删除,使之变成栈顶元素才可以。在c++中有专门的STL容器专门供程序员调用。

stack的头文件:

#include< stack >
当然在c++中也可用万能头文件
#include< bits/stdc++.h >

stack的声明与使用:

stack<数据类型> 变量名:
例如:stack< int > s ;声明一个栈s,栈元素为int类型。

stack的一些常用函数:

  • top():返回栈顶元素。如果栈空,返回值未定义。
  • push():将元素压入栈顶。
  • pop():将栈顶元素弹出。
  • size():返回栈中元素的个数。
  • empty():返回栈是否为空,栈空为true。

stack的简单使用:

#include<bits/stdc++.h>
using namespace std;
int main()
{
	stack <int>s;
	for(int i = 1;i <= 5;i++)
	{
		s.push(i);
		cout<<"Push "<<i<<" into the stack."<<endl;
	}
	cout<<"The stack has "<<s.size()<<" elements."<<endl;
	cout<<"The stack is empty? "<<s.empty()<<endl;
	cout<<"The top element of the stack is:"<<s.top()<<endl;
	int x = s.top();
	s.pop();
	cout<<"The poped element is "<<x<<",now the stack size is :"<<s.size()<<endl;
	for(int i=0;i<4;i++)
	{
		int x = s.top();
		s.pop();
		cout<<"The poped element is "<<x<<endl;
	}
	cout<<"The stack is empty? "<<s.empty()<<endl;;
	return 0;
 } 
  • 运行结果

Push 1 into the stack.
Push 2 into the stack.
Push 3 into the stack.
Push 4 into the stack.
Push 5 into the stack.
The stack has 5 elements.
The stack is empty? 0
The top element of the stack is:5
The poped element is 5,now the stack size is :4
The poped element is 4
The poped element is 3
The poped element is 2
The poped element is 1
The stack is empty? 1

附用指针实现栈的结构

#include<bits/stdc++.h>
using namespace std;
//栈元素的结构定义 
typedef struct snode
{
	int element;//元素
	struct snode *next;//下一节点指针 
}StackNode,*slink;

//申请栈元素空间 
slink NewStackNode()
{
	return (slink)malloc(sizeof(StackNode));//返回栈元素节点空间 
}

//定义栈的结构 
typedef struct lstack
{
	slink top;
}Lstack,*Stack;

//栈的初始化 
Stack StackInit()
{
	Stack S = (Stack)malloc(sizeof(*S));
	S->top = 0;
	return S;
} 

//判断是否栈空 
int StackEmpty(Stack S)
{
	return S->top == 0;
}
 
//返回栈顶元素
int StackTop(Stack S)
{
	if(StackEmpty(S))
		return 0;
	return S->top->element;
}

//压栈

void Push(Stack S,int x)
{
	slink p = NewStackNode();
	p->element = x;
	p->next = S->top;
	S->top = p;
}

//出栈
int Pop(Stack S)
{
	if(StackEmpty(S))
		return 0;
	int x = S->top->element;
	slink p = S->top;
	S->top = p->next;
	free(p);
	return x;
} 

经典例题传送门:

相关题目的解析与实现:

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值