1. 程式人生 > >用順序棧建立雙棧結構

用順序棧建立雙棧結構

雙棧結構,即兩端都可以入棧,但無論從哪一端,仍遵從LIFO

include

define MAXSIZE 1024

typedef struct dStack{
elemtype data[MAXSIZE];
int top[3];
}DSequenStack;
DSequenStack *Init_1_DSequenStack(int m)
{
DSequenStack P=(DSequenStack )malloc(sizeof(DSequenStack)*m);
if(P==NULL)return P;
P->top[0]=m;
P->top[1]=-1;
P->top[2]=m;
return P;
}
/判空

/
int DS_Empty(DSequenStack *P)
{
if(P->top[1]==-1&&P->top[2]==P->top[0])
return 1;
else return 0;
}
/判滿/
int DS_Full(DSequenStack *P)
{
if(P->top[1]+1==P->top[2])
return 1;
else return 0;
}
/入棧/
int Push_1(DSequenStack *P,elemtype x1,elemtype x2)
{
if(DS_Full(P))return 0;
P->top[1]++;
P->data[P->top[1]]=x1;
P->top[2]–;
P->data[P->top[2]]=x2;

return 1;

}
/出棧/
int Pop_1(DSequenStack *P,elemtype x1,elemtype x2)
{
if(DS_Empty(P))return 0;
printf(“Top[1]:\t”);
while(P->top[1]!=-1){
x1=P->data[P->top[1]];
P->top[1]–;
printf(“\t%d\t”,x1);
}
printf(“\n”);
printf(“Top[2]:\t”);
while(P->top[2]!=P->top[0])
{
x2=P->data[P->top[2]];
P->top[2]++;
printf(“\t%d\t”,x2);
}
printf(“\n”);

return 1;

}

void main()
{
int x=1,y=2;

DSequenStack * P=Init_1_DSequenStack(10);

if(P==NULL)return ;
while(!DS_Full(P))
{
    Push_1(P,x,y);
    x++;
    y++;
}

Pop_1(P,x,y);

}