#include<stdio.h>
#define maxsize 10
typedef int ElemType;
typedef struct stack{
ElemType data[maxsize];
int top;
int bottom;
}stack;
//初始化栈
void init_stack(stack *s){
s->bottom = maxsize;
s->top = -1;
}
//录入数据建栈
void create_stack(stack *s){
int n,n1,i,select,j;
printf("请输入你想从栈底还是栈头创建栈,1.代表头建,2.代表尾建\n");
scanf("%d",&select);
if(select == 1){
printf("请输入你想创建几个数据\n");
scanf("%d",&n);
if(n<=0||n>maxsize){
printf("输入范围有误\n");
}else{
for(i=0;i<n;i++){
if(s->top == s->bottom-1){
printf("栈满无法再添加\n");
break;
}else{
printf("请输入第%d个数据\n",i+1);
scanf("%d",&s->data[i]);
s->top = i;
}
}
}
}else if(select == 2){
printf("请输入你想创建几个数据\n");
scanf("%d",&n);
if(n<=0||n>maxsize){
printf("输入范围有误\n");
}else{
for(i=maxsize-1,j=0;i>=0,j<n;i--,j++){
if(s->top == s->bottom-1){
printf("栈满无法再添加\n");
break;
}else{
printf("请输入第%d个数据\n",j+1);
scanf("%d",&s->data[i]);
s->bottom = i;
}
}
}
}
}
//栈插入元素
void insert_stack(stack *s){
int n,select,m;
n = s->top;
m = s->bottom;
if(s->top == s->bottom-1){
printf("栈满无法插入\n");
}else{
printf("请选择插入的位置1.代表前栈插入2.代表后栈插入\n");
scanf("%d",&select);
if(select == 1){
printf("请输入你要插入的元素\n");
scanf("%d",&s->data[n+1]);
s->top++;
}else if(select == 2){
printf("请输入你要插入的元素\n");
scanf("%d",&s->data[m-1]);
s->bottom--;
}
}
}
//删除栈内元素
void delete_stack(stack *s){
int select;
if(s->top == -1 && s->bottom == maxsize){
printf("栈空无法删除\n");
}else{
printf("请选择从1.前栈删除还是2.后栈删除\n");
scanf("%d",&select);
if(s->top == -1&&select == 1){
printf("前栈为空不可选择再次删除\n");
}else if(select == 2&&s->bottom == maxsize){
printf("后栈为空不可选择再次删除\n");
}else{
if(select == 1){
s->top--;
}else{
s->bottom++;
}
}
}
}
//取栈顶元素
void get_top_stack(stack *s){
int select;
if(s->top == -1 && s->bottom == maxsize){
printf("栈空无法删除\n");
}else{
printf("请选择从1.前栈取还是从2.后栈取\n");
scanf("%d",&select);
if(s->top == -1&&select == 1){
printf("前栈为空不可再取\n");
}else if(select == 2&&s->bottom == maxsize){
printf("后栈为空不可再取\n");
}else{
if(select == 1){
printf("%d\n",s->data[s->top]);
}else{
printf("%d\n",s->data[s->bottom]);
}
}
}
}
//遍历栈
void print_stack(stack *s){
int n,m;
n = s->top;
m = s->bottom;
if(n == -1&&m == maxsize){
printf("该栈为空\n");
}else{
printf("头栈\n");
while(n != -1){
printf("%d ",s->data[n]);
n--;
}
printf("\n");
printf("尾栈\n");
while(m != maxsize){
printf("%d ",s->data[m]);
m++;
}
printf("\n");
}
}
//栈菜单
void mune(){
printf("1.代表初始化栈\n");
printf("2.代表创建栈\n");
printf("3.代表往栈内插入元素\n");
printf("4.代表删除栈内元素\n");
printf("5.代表取栈顶元素\n");
printf("6.打印栈内元素\n");
printf("7.退出系统\n");
}
int main(){
stack s;
int select,flag=1;
while(flag){
mune();
printf("请输入你想进行的操作\n");
scanf("%d",&select);
switch(select){
case 1:
init_stack(&s);
break;
case 2:
create_stack(&s);
break;
case 3:
insert_stack(&s);
break;
case 4:
delete_stack(&s);
break;
case 5:
get_top_stack(&s);
break;
case 6:
print_stack(&s);
break;
case 7:
flag = 0;
break;
}
}
return 0;
}
两栈空间共享(顺序栈)
于 2022-10-19 14:48:46 首次发布