1. 兩棧共享空間結構
typedef struct
{
SElemType data[MAXSIZE];
int top1; /* 棧1棧頂指針 */
int top2; /* 棧2棧頂指針 */
}SqDoubleStack;
2. 構造一個空棧S
Status InitStack(SqDoubleStack *S)
{
S->top1=-1;
S->top2=MAXSIZE;
return OK;
}
3. 把S置為空棧
Status ClearStack(SqDoubleStack *S)
{
S->top1=-1;
S->top2=MAXSIZE;
return OK;
}
4.若棧S為空棧,則返回TRUE,否則返回FALSE
Status StackEmpty(SqDoubleStack S)
{
if (S.top1==-1 && S.top2==MAXSIZE)
return TRUE;
else
return FALSE;
}
5.返回S的元素個數,即棧的長度
int StackLength(SqDoubleStack S)
{
return (S.top1+1)+(MAXSIZE-S.top2);
}
6.插入元素e為新的棧頂元素
Status Push(SqDoubleStack *S,SElemType e,int stackNumber)
{
if (S->top1+1==S->top2) /* 棧已滿,不能再push新元素了 */
return ERROR;
if (stackNumber==1) /* 棧1有元素進棧 */
S->data[++S->top1]=e; /* 若是棧1則先top1+1後給數組元素賦值。 */
else if (stackNumber==2) /* 棧2有元素進棧 */
S->data[--S->top2]=e; /* 若是棧2則先top2-1後給數組元素賦值。 */
return OK;
}
7.若棧不空,則刪除S的棧頂元素,用e返回其值,並返回OK;否則返回ERROR
Status Pop(SqDoubleStack *S,SElemType *e,int stackNumber)
{
if (stackNumber==1)
{
if (S->top1==-1)
return ERROR; /* 說明棧1已經是空棧,溢出 */
*e=S->data[S->top1--]; /* 將棧1的棧頂元素出棧 */
}
else if (stackNumber==2)
{
if (S->top2==MAXSIZE)
return ERROR; /* 說明棧2已經是空棧,溢出 */
*e=S->data[S->top2++]; /* 將棧2的棧頂元素出棧 */
}
return OK;
}
8.顯示全部元素
Status StackTraverse(SqDoubleStack S)
{
int i;
i=0;
while(i<=S.top1)
{
visit(S.data[i++]);
}
i=S.top2;
while(i
Status visit(SElemType c)
{
printf("%d ",c);
return OK;
}
參考<<大話數據結構>>