/*
* stack2.c
*
* Created on: Dec 4, 2012
* Author: fsxchen
* 两个栈共享空间,前提是,栈中的数据类型一致
*/
#include
#define MAXSIZE 10
typedef struct
{
int data[MAXSIZE];
int top1;
int top2;
}SqDoubleStack;
void InitDstack(SqDoubleStack *s)
{
s->top1 = -1;
s->top2 = MAXSIZE;
}
void PushDstack(SqDoubleStack *s, int stackNum)
{
int val;
printf("请输入你要入栈的值");
scanf("%d", &val);
if(s->top1 + 1 == s->top2)
printf("ERROR");
else if(stackNum == 1)
s->data[++s->top1] = val;
else
s->data[--s->top2] = val;
}
int PopDstack(SqDoubleStack *s,int stackNum)
{
int i;
if(stackNum == 1)
{
if(s->top1 == -1)
{
printf("空栈!");
return -1;
}
i = s->data[s->top1--];
return i;
}
else if(stackNum == 2)
{
if(s->top2 == MAXSIZE)
{
printf("空栈!");
return -1;
}
i = s->data[s->top2++];
return i;
}
}
双栈的实现:两个栈共用一段空间,栈空间满的条件是top1==top2,这种方式,可以节约空间,但是栈顶的指向,一个是从大到小。一个则是从小到大,所以要注意top的变化!