栈
栈是一种重要的数据结构,是限定仅在表尾进行插入或删除操作的线性表。表尾称为栈顶,表头称为栈底。栈的修改是按照后进先出的原则的。栈可以用顺序表和链表实现,在这里用链表实现最基本的入栈,弹栈操作。
代码
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct data
{
int data;
}datas;
struct stack
{
struct stack* base;
struct stack* top;
struct stack* next;
struct data* info;
};
stack* InitStack()//初始化
{
struct stack* s;
s = new stack;
s->base = s->top;
return s->base;
}
stack* PushStack(struct stack* s)//压栈
{
int e;//栈元素
struct stack* base,*top;
cout << "请输入入栈数据,输入-1表示结束" << endl;
while (true)
{
cin >> e;
if (e == -1)
break;
else
{
base = new stack;
top = new stack;
top->info = new datas;
top->info->data = e;
top->next = s;
s = top;
}
}
return s;
}
stack* PopStack(struct stack* s)//弹栈
{
struct stack* s1;
cout << "请输入需要弹出的个数" << endl;
int n;
cin >> n;
for(int i=0;i<n;i++)
{
s1 = new stack;
s1 = s;
cout << "弹出的是:" << s->info->data << endl;
s = s->next;
free(s1);
}
return s;
}
int main()
{
struct stack* s,*s1,*s2;
s = InitStack();
s1 = PushStack(s);
s2 = PopStack(s1);
system("pause");
return 0;
}