简单的栈
typedef struct
{
int data[maxn];
int top;
}SqStack;
void initstack(SqStack *S)
{
S->top=-1;
return ;
}
void inputpush(SqStack *S)
{
int x;
cin>>x;
if(S->top==maxn-1)
return ;
while(x!=-1)
{
S->top++;
S->data[S->top]=x;
cin>>x;
}
}
void printpop(SqStack *S)
{
while(S->top!=-1)
{
cout << S->data[S->top] << ' ';
S->top--;
}
cout << endl;
}
int main()
{
SqStack S;
initstack(&S);
inputpush(&S);
printpop(&S);
return 0;
}
两栈共享空间
typedef struct
{
int data[maxn];
int top1;
int top2;
}SqDoubleStack;
void initstack(SqDoubleStack *S)
{
S->top1=-1;
S->top2=maxn;
}
void inputstack(SqDoubleStack *S,int stacknumber)
{
if(S->top1+1==S->top2)
return ;
int x;
cin>>x;
while(x!=-1)
{
if(stacknumber==1)
S->data[++S->top1]=x;
else if(stacknumber==2)
S->data[--S->top2]=x;
cin>>x;
}
}
void printstack(SqDoubleStack *S,int stacknumber)
{
if(stacknumber==1)
{
while(S->top1!=-1)
{
cout << S->data[S->top1--] << ' ';
}
}
else if(stacknumber==2)
{
while(S->top2!=maxn)
{
cout << S->data[S->top2++] << ' ';
}
}
cout << endl;
}
int main()
{
SqDoubleStack S;
initstack(&S);
int num;
cin>>num;
inputstack(&S,num);
cin>>num;
printstack(&S,num);
return 0;
}
链栈
typedef struct Node
{
int data;
struct Node *next;
}StackNode,*LinkStackPtr;
typedef struct
{
LinkStackPtr top;
int cnt;
}LinkStack;
void initstack(LinkStack *S)
{
S->top=NULL;
S->cnt=0;
}
void inputlinkstack(LinkStack *S)
{
int x;
cin>>x;
while(x!=-1)
{
LinkStackPtr p=(LinkStackPtr)malloc(sizeof(Node));
p->data=x;
p->next=S->top;
S->top=p;
S->cnt++;
cin>>x;
}
}
void printlinkstack(LinkStack *S)
{
LinkStackPtr p;
while(S->top!=NULL)
{
p=S->top;
cout << p->data << ' ';
S->top=S->top->next;
free(p);
S->cnt--;
}
}
int main()
{
LinkStack S;
initstack(&S);
inputlinkstack(&S);
printlinkstack(&S);
}