【数据结构】栈顺序存储的实现
//栈的顺序存储实现
#include<iostream>
using namespace std;
#define ERROR -1
#define Maxsize 10
typedef int element;
//栈的存储结构:一个一维数组和一个记录栈顶元素位置的变量组成
typedef struct {
element data[Maxsize];
int top;
}stack;
//入栈
void push(stack *s,element item)
{
if (s->top == Maxsize - 1)
cout << "栈满,无法入栈" << endl;
else
{
s->data[++(s->top)] = item;//两个操作:1.top+1 2.赋值
}
}
//出栈
element pop(stack *s,element *e)
{
if (s->top == -1)
{
cout << "栈为空,无法出栈" << endl;
return ERROR;
}
else
{
int tmp=s->top;
*e = s->data[tmp];
cout << "出栈元素为:" << *e<<endl;
s->top--;
}
}
//栈的初始化
void Initail(stack *s)
{
s->top = -1;
}
//遍历栈中元素
void visit(stack *s)
{
int tmp = s->top;
cout << "栈中元素为:" << endl;
for (tmp;tmp >= 0;tmp--)
{
cout << s->data[tmp]<<endl;
}
cout << endl;
}
int main()
{
stack s;
int i,count,count1,num2;
element num;
Initail(&s);
cout << "请输入入栈的个数:";
cin >> count;
cout << "请输入入栈元素:"<<endl;
for (i=0;i<count;i++)
{
cin >> num;
push(&s,num);
}
cout << "请输入出栈的个数:";
cin >> count1;
for (i = 0;i<count1;i++)
{
pop(&s, &num2);
}
visit(&s);
return 0;
}
结果: