以下是两栈共享空间的代码实现,C语言
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define stduent student
#define max 5
struct stduent{
int data[max];
int top1;
int top2;
};
int push(struct stduent *stack,int e,int stacktype){
char a;
if(stack->top1+1==stack->top2){
printf("栈满,最后一个元素无法录入");
return 0;
}
if(stacktype==1){
stack->data[++stack->top1] = e;
}else if(stacktype==2){
stack->data[--stack->top2] = e;
}
printf("是否继续输入:(y/n)");
scanf("\n");
scanf("%c", &a);
if(a=='y'){
return 1;
}else{
return 0;
}
}
void put(struct stduent *stack,int stacktype){
int t1, t2;
t1 = stack->top1, t2 = stack->top2;
if(stacktype==1){
if(stack->top1==-1){
printf("栈空");
return;
}else{
printf("以下为栈1元素:\n");
while(stack->top1!=-1){
printf("%d ", stack->data[stack->top1--]);
}
printf("\n遍历完毕");
}
}else if(stacktype==2){
if(stack->top2==max){
printf("栈空");
return;
}else{
printf("以下为栈2元素:\n");
while(stack->top2!=max){
printf("%d ", stack->data[stack->top2++]);
}
printf("\n遍历完毕");
}
}else{
if(stack->top1==-1&&stack->top2==max){
printf("栈空");
return;
}else{
printf("以下为全栈元素:\n");
while(stack->top1!=-1){
printf("%d ", stack->data[stack->top1--]);
}
while(stack->top2!=max){
printf("%d ", stack->data[stack->top2++]);
}
printf("\n遍历完毕");
}
}
stack->top1 = t1, stack->top2 = t2;//遍历完成后还原指针
}
void pop(struct student *stack,int *e,int stacktype){
if(stacktype==1){
if(stack->top1==-1){
printf("栈空");
return;
}else{
*e = stack->data[stack->top1--];
}
}else{
if(stack->top2==max){
printf("栈空");
return;
}else{
*e = stack->data[stack->top2++];
}
}
printf("取出的栈%d顶的元素为:%d", stacktype, *e);
}
int main(){
struct student *stack = (struct student *)malloc(sizeof(struct student));
int data, type, e;
stack->top1 = -1;
stack->top2 = max;
do{
printf("请输入元素 栈序号(1/2):\n");
scanf("%d %d", &data, &type);
}while (push(stack, data, type));
printf("\n请输入要打印的栈(同时打印两栈请输入3): ");
scanf("%d", &type);
put(stack, type);
printf("\n请输入要提取栈顶元素的栈: ");
scanf("%d", &type);
pop(stack, &e, type);
printf("\n请输入要打印的栈(同时打印两栈请输入3): ");
scanf("%d", &type);
put(stack, type);
return 0;
}
有帮助的话给个赞呗 ^_^