1-顺序栈入栈
2-顺序栈出栈
3-链栈入栈
4-链栈出栈
//****************************************
//数据结构:顺序栈和链栈
//算法:出栈和入栈
//首次编辑时间:2020/05/27
//最后修改时间:2020/05/28
//****************************************
#include<stdio.h>
#include<stdlib.h>
typedef struct seqstack//顺序栈
{
int data[20];
int top;
}seqstack;
typedef struct linkstack//链栈
{
int data;
struct linkstack *next;
}node;
seqstack creat_seqstack();//创建顺序栈
void show_seqstack();//遍历打印显示顺序栈
seqstack push_seqstack();//顺序栈入栈
seqstack pop_seqstack();//顺序栈出栈
node* creat_linkstack();//创建链栈
void show_linkstack();//遍历打印显示链栈
node* push_linkstack();//链栈入栈
node* pop_linkstack();//链栈出栈
int main()
{
seqstack st = creat_seqstack();
node *top = creat_linkstack();
while (1)
{
int action;
printf("*****************************\n");
printf("选择:\n");
printf("0-结束退出\n");
printf("1-顺序栈入栈\n");
printf("2-顺序栈出栈\n");
printf("3-链栈入栈\n");
printf("4-链栈出栈\n");
printf("-----------------------------\n");
printf("原顺序栈:");
show_seqstack(st);
printf("\n");
printf("原链栈:");
show_linkstack(top);
printf("\n");
printf("-----------------------------\n");
printf("输入选择序号:");
scanf("%d", &action);
printf("-----------------------------\n");
switch (action)
{
case 0:return 0;
case 1:st = push_seqstack(st);printf("新顺序栈:");show_seqstack(st);printf("\n");break;
case 2:st = pop_seqstack(st);printf("新顺序栈:");show_seqstack(st);printf("\n");break;
case 3:top = push_linkstack(top);printf("新链栈:");show_linkstack(top);printf("\n");break;
case 4:top = pop_linkstack(top);printf("新链栈:");show_linkstack(top);printf("\n");break;
default:printf("无效序号!");
}
}
}
seqstack creat_seqstack()//创建顺序栈
{
seqstack st = { {1,2,3,4,5}, 4 };//创建时顺便放入5个数
return st;
}
void show_seqstack(seqstack st)//遍历打印显示顺序栈
{
while(st.top != -1)
printf("%d ",st.data[st.top--]);
}
seqstack push_seqstack(seqstack st)//顺序栈入栈
{
int value;
printf("请输入入栈值:");
scanf("%d", &value);
st.data[++(st.top)] = value;
return st;
}
seqstack pop_seqstack(seqstack st)//顺序栈出栈
{
--st.top;
return st;
}
node* creat_linkstack()//创建链栈
{
node *top, *p;
int i;
top = (node*)malloc(sizeof(node));
top->next = NULL;
top->data = 1;//创建时顺便放入5个数
for (i = 2;i < 6;i++)
{
p = (node*)malloc(sizeof(node));
p->next = top;
p->data = i;
top = p;
}
return top;
}
void show_linkstack(node *top)//遍历打印显示链栈
{
while (top != NULL)
{
printf("->%d", top->data);
top = top->next;
}
}
node* push_linkstack(node *top)//链栈入栈
{
int value;
node *p;
printf("请输入入栈值:");
scanf("%d", &value);
p = (node*)malloc(sizeof(node));
p->data = value;
p->next = top;
return p;
}
node* pop_linkstack(node *top)//链栈出栈
{
node *d = top;
top = top->next;
free(d);
return top;
}