/*顺序栈的实现*/
#include<stdio.h>
#define stacksize 50
#define TRUE 1
#define FALSE 0
typedef struct{
char elem[stacksize];
int top;
}sequencestack;
/*顺序栈的初始化*/
void initial(sequencestack * S)
{
S->top=-1;//构造一个空栈
printf("initial sequence-stack success!\n");
fflush(stdout);
}
/*顺序栈进栈操作*/
int sequencepushstack(sequencestack *S)
{
char c;
int flag=1;
if(S->top==stacksize-1)
{
printf("The stack is full !");
fflush(stdout);
return FALSE;
}
else
{
while(flag)
{
c=getchar();
if(c!='$')
{
S->top++;
S->elem[S->top]=c;
}
else
{
flag=0;
printf("Stack success !\n");
fflush(stdout);
}
}
}
return TRUE;
}
/*弹出栈顶元素*/
int sequencepopstack(sequencestack *S)
{
if(S->top==-1)
{
printf("stack empty!\n");
fflush(stdout);
}
else
{
printf("The value of the stack top element is %c\n",S->elem[S->top]);
fflush(stdout);
S->top--;
}
return TRUE;
}
/*所有元素出栈*/
int popallelement(sequencestack *S)
{
if(S->top==-1)
{
printf("\n stack empty!\n");
fflush(stdout);
return TRUE;
}
else
{
printf("%2c",S->elem[S->top]);
fflush(stdout);
S->top--;
popallelement(S);
}
return FALSE;
}
int main(void)
{
sequencestack *S;
/*形参的星号是指指针,就是结构体类型的指针,函数形参是一个结构体指针,
* 实参也需要一个该结构体类型的指针,也就是要实参是一个地址传给形参
* 故在函数调用是使用的是&符号,就是区地址,将结构体变量的地址传过去
* 这样在函数里对于形参的修改就是对实参结构体变量的修改。*/
initial(&S);
printf("Please input the element to enter the stack and end with $ \n");
fflush(stdout);
sequencepushstack(&S);
sequencepopstack(&S);
printf("The out-of-stack elements are as follows... \n");
fflush(stdout);
popallelement(&S);
return 0;
}
调试结果
initial sequence-stack success!
Please input the element to enter the stack and end with $
edrftgyhujikol123456plmjkn$
Stack success !
The value of the stack top element is n
The out-of-stack elements are as follows...
k j m l p 6 5 4 3 2 1 l o k i j u h y g t f r d e
stack empty!