stack.h
#ifndef stack_h__
#define stack_h__
#include <stdio.h>
#include <stdlib.h>
enum boolean{FALSE, TRUE};
typedef enum boolean Bool;
typedef int ElementType;
typedef struct stack_def{
int top;
ElementType * elements;
int MaxSize;
}Stack;
void FreeStack(Stack* s);
void MakeEmpty(Stack * s);
Bool IsEmpty(Stack* s);
Bool IsFull(Stack* s);
Bool InitStack(Stack* s, int sz);
Bool Push(Stack* s, ElementType x);
ElementType* Pop(Stack* s);
Bool GetTop(Stack* s, ElementType* e);
#endif // stack_h__
stack.c
#include "stack.h"
void FreeStack(Stack* s){
free(s->elements);
}
void MakeEmpty(Stack * s){
s->top = -1;
}
Bool IsEmpty(Stack* s){
return(Bool)(s->top==-1);
}
Bool IsFull(Stack* s){
return (Bool)(s->top==s->MaxSize-1);
}
Bool InitStack(Stack* s, int sz){
if (sz > 0){
s->MaxSize = sz;
s->top = -1;
s->elements = (ElementType*)malloc(sizeof(ElementType)*sz);
if (s->elements == NULL)
puts("No Eniugh Memory.");
else
return TRUE;
}
else{
puts("The stack size error.");
}
return FALSE;
}
Bool Push(Stack* s, ElementType x){
if (!IsFull(s)){
s->elements[++(s->top)] = x;
return TRUE;
}
return FALSE;
}
ElementType* Pop(Stack* s){
if (!IsEmpty(s)){
return s->elements + s->top--;
}
return NULL;
}
Bool GetTop(Stack* s, ElementType* e){
if (!IsEmpty(s)){
*e = s->elements[s->top];
return TRUE;
}
return FALSE;
}
main.c
#include "stack.h"
int main(){
/*main 主要测试栈的函数的使用*/
Stack s;
ElementType e;
InitStack(&s, 5);
if (IsEmpty(&s))
puts("Empty!");
else
puts("Not Empty");
Push(&s,1);
Push(&s,2);
Push(&s,3);
Push(&s,4);
Push(&s,5);
if (Push(&s,6))
puts("Push OK");
else
puts("Push Not OK");
if (IsFull(&s))
puts("Full");
else
puts("Not Full");
GetTop(&s, &e);
printf("%d
", e);
Pop(&s);
e = *Pop(&s);
printf("%d
", e);
Pop(&s);
Pop(&s);
Push(&s, 8);
e = *Pop(&s);
printf("%d
", e);
e = *Pop(&s);
printf("%d
", e);
if (!Pop(&s))
puts("empty");
return 0;
}