顺序栈的C语言实现
#include "stdafx.h"
//初始长度为100
#define StackSize 100
typedef char DataType;
typedef struct stack{
DataType data[StackSize];
int top;
}SqStack;
//初始化栈
void InitStack(SqStack *S)
{
S->top = -1;
}
//判断是否为空
int StackEmpty(SqStack *S)
{
return S->top == -1;
}
//判断是否满栈
int StackFull(SqStack *S)
{
return S->top == StackSize-1;
}
//入栈
void push(SqStack *S,DataType d)
{
if (StackFull(S))
{
printf("Stack is full!");
exit(-1);
}
S->data[++S->top] = d;
}
//出栈
DataType pop(SqStack *S)
{
if (StackEmpty(S))
{
printf("Stack is empty!\n");
exit(-1);
}
return(S->data[S->top--]);
}
//显示
void disp(SqStack *S)
{
if (StackEmpty(S))
{
printf("Stack is empty!\n");
exit(-1);
}
int count = S->top;
printf("The elements of stack are:\n");
while(S->top != -1)
{
printf("%c\n",S->data[S->top--]);
}
S->top = count;
}
int main()
{
SqStack *S;
S = (SqStack *)malloc(sizeof(SqStack));
printf("Initialize the stack.\n");
InitStack(S);
push(S,'a');
push(S,'b');
push(S,'c');
push(S,'d');
disp(S);
printf("pop a element\n");
DataType aa = pop(S);
disp(S);
DataType bb = pop(S);
disp(S);
DataType cc = pop(S);
disp(S);
DataType dd = pop(S);
disp(S);
DataType ee = pop(S);
disp(S);
}