一次性定义两个栈
第一个栈的栈顶 top1 从-1开始递增
第二个栈的栈顶 top2 从maxlen开始递减
共享的意思是可以共享存储空间,即top1可以到maxlen-1,top2可以到0
栈满的标志是:top1+1 = top2
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "time.h"
#define maxlen 20 /* 存储空间初始分配量 */
/* 两栈共享空间结构 */
typedef struct
{
int data[maxlen];
int top1; /* 栈1栈顶指针 */
int top2; /* 栈2栈顶指针 */
}doubleStack;
int push(doubleStack* L, int value, int choose_stack)
{
if (L->top1 + 1 == L->top2)
{
printf("栈满\n");
return 0;
}
if (choose_stack == 1)
{
L->top1++;
L->data[L->top1] = value;
}
else if(choose_stack == 2)
{
L->top2--;
L->data[L->top2] = value;
}
else
{
printf("输入错误\n");
return 0;
}
return 1;
}
int pop(doubleStack* L, int *value,int choose_stack)
{
if (choose_stack == 1)
{
if (L->top1 == -1)
{
printf("栈1已满\n");
return 0;
}
*value = L->data[L->top1];
L->top1--;
}
else if (choose_stack == 2)
{
if (L->top2 == maxlen)
{
printf("栈2已满\n");
return 0;
}
*value = L->data[L->top2];
L->top2++;
}
return 1;
}
int seelist(doubleStack L)
{
printf("\n栈1:");
for (int i = 0; i <= L.top1; i++)
{
printf("%d ", L.data[i]);
}
printf("\n栈2:");
for (int j = maxlen-1;j>= L.top2; j--)
{
printf("%d ", L.data[j]);
}
return 1;
}
int initlist(doubleStack* L)
{
L->top1 = -1;
L->top2 = maxlen;
return 1;
}
int main()
{
int value, i, j;
doubleStack L;
initlist(&L);
for (i = 0; i < 7; i++)
{
push(&L, i, 1);
}
for (i = 0; i < 4; i++)
{
push(&L, i, 2);
}
seelist(L);
pop(&L, &value, 1);
pop(&L, &value, 1);
pop(&L, &value, 2);
seelist(L);
printf("\n%d", value);
}