根據書上描述,共享棧的特點是:兩個棧頂,置放在數組兩頭,入棧迎面相向,相遇時棧滿,看圖示:
主要處理兩步工作:
第一,棧空的標志。這里沿用前面的約定,左棧用-1,而右棧用MAXSIZE,也就是放在數組的最左右兩端。
第二,判滿。這里采用左棧+1=右棧表明棧滿。
此外,還需要一個狀態標志flag,讓用戶選擇是哪一個棧進行操作。綜合看過幾本書的各自優點,進行記錄
#include <iostream> using namespace std; #define MAXSIZE 20 #define OK 1 #define ERROR 0 typedef struct { int data[MAXSIZE]; int top[2];/*top[0]:左棧,top[1]:右棧*/ }*SeqStack,Stack; void InitStack(SeqStack &S)/*初始化*/ { S->top[0]=-1; S->top[1]=MAXSIZE; } int PushStack(SeqStack &S,int e,int flag)/*入棧*/ { if(S->top[0]+1==S->top[1])/*棧滿的判定*/ { return ERROR; } switch(flag)/*檢測標志flag*/ { case 0: /*左棧*/ ++S->top[0]; S->data[S->top[0]]=e; break; case 1: /*右棧*/ --S->top[1]; S->data[S->top[1]]=e; break; default: return ERROR; } return OK; } int PopStack(SeqStack &S,int &e,int flag)/*出棧*/ { if(S->top[0]==-1 || S->top[1]==MAXSIZE)/*棧空判定*/ return ERROR; switch(flag)/*檢測標志flag*/ { case 0:/*左棧*/ e=S->data[S->top[0]]; --S->top[0]; break; case 1:/*右棧*/ e=S->data[S->top[1]]; --S->top[1]; break; default: return ERROR; } return OK; } int main(void) { int e; SeqStack S=(SeqStack)malloc(sizeof(Stack));/*堆中分配*/ InitStack(S);/*初始化*/ PushStack(S,12,1);/*右入棧*/ cout<<"S.top="<<S->top[1]<<endl; cout<<"S.top="<<S->top[0]<<endl; PushStack(S,10,0);/*左入棧*/ cout<<"S.top="<<S->top[1]<<endl; cout<<"S.top="<<S->top[0]<<endl; PopStack(S,e,0);/*左出棧*/ cout<<"S.top="<<S->top[1]<<endl; cout<<"S.top="<<S->top[0]<<endl; free(S);/*釋放內存*/ return 0; }