栈是一种LIFO表,即后进先出表,可以把栈理解为 火车调度时的情况。先进入一节车厢,记为1,再进入一节车厢,记为2,。1想要出站,必须2先出站。也可以理解为洗盘子的情形,洗完一个盘子后放在最下方,再洗一个放在上一个盘子的上方,最后需要取用盘子的时候就从最上面的一个取。
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 20
typedef int ElemType;
typedef struct Stack
{
ElemType *Base;
int Length;
}Stack, *PtrStack;
//creat an empty stack
PtrStack InitStack();
//push an element into stack
void Push(PtrStack S, ElemType E);
//Pop an element and return it
ElemType Pop(PtrStack S);
//print elements of stack
void PrintStack(PtrStack S);
int main()
{
PtrStack S = InitStack();
Push(S, 1);
Push(S, 2);
Push(S, 4);
Push(S, 3);
PrintStack(S);
printf("%d ", Pop(S));
printf("%d\n", Pop(S));
PrintStack(S);
return 0;
}
PtrStack InitStack()
{
PtrStack S = (PtrStack)malloc(sizeof(Stack));
S->Base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
S->Length = 0;
return S;
}
void Push(PtrStack S, ElemType E)
{
if(S->Length == STACK_INIT_SIZE)
{
printf("Stack is full\n");
exit(1);
}
*(S->Base + S->Length) = E;
S->Length++;
}
ElemType Pop(PtrStack S)
{
if(!S->Length)
{
printf("Stack is empty\n");
exit(1);
}
S->Length--;
return *(S->Base + S->Length);
}
void PrintStack(PtrStack S)
{
for(int i = 0 ; i < S->Length ; i ++)
printf("%d%c", *(S->Base + i), (i == S->Length - 1) ? '\n' : ' ');
}