栈(stack)
1.什么是栈?
栈(stack)是一种只能在表的一端进行插入和删除的线性表。是一种一对一的线性关系。因为只能在栈顶进行插入和删除.这种结构特性决定了栈只能的性质:后进先出(Last In First Out),结构决定性质,性质决定用途,所以凡是具有后进先出特性的都可以用栈来描述这里主要介绍c++标准库中栈的接口及实现
2.stl中的stack
class stack<>模板实例化出一个栈stack(也称为LIFO,Last In First Out).你可以使用push()将元素置入stack的栈顶中(top),也可以使用pop()将栈顶元素弹出栈中,为了使用c++标准库中的stack,必须包含头文件
3.stack 的核心接口
push()向栈中压入一个数据元素,使之成为新的栈顶
top()取栈顶元素.使用之前必须对栈进行判空。如果栈为空,会导致未定义行为
pop()弹出栈顶元素,使用前必须对栈进行判空。如果栈为空,会导致未定义行为
4.实例代码
#include<stack>
#include<iostream>
using namespace std;
int main(void)
{
//测试将{1,2,3,4,5,6}入栈.
stack<int> int_stack;//int_stack为一个栈,用来存储int数据类型
int_stack.push(1);//将数据压入栈中,成为新的栈顶元素
if(!int_stack.empty())//取栈顶元素时top()必须判空,否则会导致未定义行为
cout<<int_stack.top()<<"入栈"<<endl;
if(!int_stack.empty())
int_stack.push(2);
if(!int_stack.empty())
cout<<int_stack.top()<<"入栈"<<endl;
int_stack.push(3);
if(!int_stack.empty())
cout<<int_stack.top()<<"入栈"<<endl;
int_stack.push(4);
if(!int_stack.empty())
cout<<int_stack.top()<<"入栈"<<endl;
int_stack.push(5);
if(!int_stack.empty())
cout<<int_stack.top()<<"入栈"<<endl;
//将栈中元素依次出栈分别为{5,4,3,2,1}
cout<<"栈中元素依次出栈:"<<endl;
if(int_stack.empty())//如果栈非空,取栈顶元素top().将栈顶元素出栈pop();
cout<<"栈已空!不能再top(),pop()啦!"<<endl;
else
{
cout<<int_stack.top()<<"出栈!"<<endl;
int_stack.pop();
}
if(int_stack.empty())//如果栈非空,取栈顶元素top().将栈顶元素出栈pop();
cout<<"栈已空!不能再top(),pop()啦!"<<endl;
else
{
cout<<int_stack.top()<<"出栈!"<<endl;
int_stack.pop();
}
if(int_stack.empty())//如果栈非空,取栈顶元素top().将栈顶元素出栈pop();
cout<<"栈已空!不能再top(),pop()啦!"<<endl;
else
{
cout<<int_stack.top()<<"出栈!"<<endl;
int_stack.pop();
}
if(int_stack.empty())//如果栈非空,取栈顶元素top().将栈顶元素出栈pop();
cout<<"栈已空!不能再top(),pop()啦!"<<endl;
else
{
cout<<int_stack.top()<<"出栈!"<<endl;
int_stack.pop();
}
if(int_stack.empty())//如果栈非空,取栈顶元素top().将栈顶元素出栈pop();
cout<<"栈已空!不能再top(),pop()啦!"<<endl;
else
{
cout<<int_stack.top()<<"出栈!"<<endl;
int_stack.pop();
}
if(int_stack.empty())//如果栈非空,取栈顶元素top().将栈顶元素出栈pop();
cout<<"栈已空!不能再top(),pop()啦!"<<endl;
else
{
cout<<int_stack.top()<<"出栈!"<<endl;
int_stack.pop();
}
return 0;
}
5.测试结果
还没有评论,来说两句吧...