#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 1
#define TRUE 1
#define FALSE 1
typedef int Status;
typedef int SElemType;
#define MAXSIZE 20 /*存储空间初始分配量*/
/*两栈共享空间结构*/
typedef struct{
SElemType data[MAXSIZE];
int top1;/*栈1栈顶指针*/
int top2;/*栈2栈顶指针*/
}SqDoubleStack;
/*构造一个空栈*/
Status InitStack(SqDoubleStack *s)
{
s->top1=-1;
s->top2=MAXSIZE;
return OK;
}
/*把栈清空*/
Status ClearStack(SqDoubleStack *s)
{
s->top1=-1;
s->top2=MAXSIZE;
return OK;
}
/*判断栈是否为空*/
Status EmptyStack(SqDoubleStack s)
{
if (s.top1==-1&&s.top2==MAXSIZE)
{
return TRUE;
}
else
{
return FALSE;
}
}
/*返回栈的长度*/
int StackLength(SqDoubleStack s)
{
return (s.top1+1)+(MAXSIZE-s.top2);
}
/*插入*/
Status Push(SqDoubleStack *s, SElemType e, int stackNumber)
{
if (s->top1+1==s->top2)
return ERROR;
if (stackNumber==1)//栈1有元素进栈
{
s->data[++s->top1]=e;
}
else if (stackNumber==2)
{
s->data[--s->top2]=e;
}
return OK;
}
/*弹出*/
Status Pop(SqDoubleStack *s, SElemType *e, int stackNumber)
{
if (s->top1==-1&&s->top2==MAXSIZE)
{
return ERROR;
}
if (stackNumber==1)
{
*e=s->data[s->top1--];
}
else if (stackNumber==2)
{
*e=s->data[s->top2++];
}
return OK;
}
/*遍历栈*/
Status TraverseStack(SqDoubleStack s)
{
int i=0;
for (i=0; i<=s.top1; i++)
{
printf("%d ",s.data[i]);
}
for (i=s.top2; i<MAXSIZE; i++)
{
printf("%d ",s.data[i]);
}
printf("\n");
return OK;
}
int main()
{
int j;
SqDoubleStack s;
int e;
if(InitStack(&s)==OK)
{
for(j=1;j<=5;j++)
Push(&s,j,1);
for(j=MAXSIZE;j>=MAXSIZE-2;j--)
Push(&s,j,2);
}
printf("栈中元素依次为:");
TraverseStack(s);
printf("当前栈中元素有:%d \n",StackLength(s));
Pop(&s,&e,2);
printf("弹出的栈顶元素 e=%d\n",e);
for(j=6;j<=MAXSIZE-2;j++)
Push(&s,j,1);
printf("栈中元素依次为:");
TraverseStack(s);
return 0;
}
两栈共享空间
最新推荐文章于 2024-09-01 20:07:41 发布