栈是线性表的一种特例,其后进先出的数据结构在开发中比较常见。许多软件、应用都提供撤销的操作(ctrl+z),其实现原理就是使用了栈的数据结构。
栈是限定仅在表尾进行插入和删除操作的线性表。
通常把允许插入和删除的一端称为栈顶(top),另外一端称为栈底(bottom),不办含任何数据元素的栈称之为空栈。栈又称之为后进先出的线性表,简称LIFO结构。
既然栈属于线性表,那么栈元素之间就具有线性关系,即前驱后继关系。常用的栈操作方式有:入栈(push)和出栈(pop)。
定义栈的数据结构
struct Stack{
int data[MAXSIZE];
int top;
}myStack;
入栈操作:
void push(Stack *s,int element){
if (s->top==MAXSIZE){
cout<<"栈满"<<endl;
return;
}
s->data[s->top]=element;
cout<<s->data[S-top]<<endl;
s->top++;
}
出栈操作:
int pop(Stack *s)
{
int e;
while (s->top <= 0)
{
cout << "栈空" << endl;
return false;
}
s->top--;
e = s->data[s->top];
return e;
}
测试代码如下:
int main()
{
int n;
cout << "请输入入栈的元素个数,最大为10" << endl;
cin >> n;
cout << "入栈" << endl;
for (auto i = 0; i < n; i++)
{
push(&myStack, i);
}
cout << "---分隔符---出栈" << endl;
cout << "出栈" << endl;
int n1;
cout<<"请输入要出栈的元素的个数"<<endl;
cin>>n1;
for (auto i = 0; i < n1; i++)
{
cout<< pop(&myStack)<<endl;
}
/* cout << "---分隔符---出栈" << endl;
while (true)
{
int n2;
cout << "请输入要出栈的元素的个数" << endl;
cin >> n2;
for (auto i = 0; i < n2; i++)
{
pop(&myStack);
}
} */
return 0;
}
输出如下图所示:
代码地址:visual studio 2017
https://github.com/USuperMe/stack.git
欢迎关注公众号,不定期分享Unity3D、C#、C++数据结构和算法学习知识。