1.stack.h
1 #include2 #include 3 4 #define N 100 5 6 struct stack 7 { 8 int data[N]; 9 int top;//标识栈顶10 };11 12 typedef struct stack Stack;//stack别名13 14 void init(Stack *p);//初始化15 int isempty(Stack *p);//判断栈是否空16 int isfull(Stack *p);//判断栈溢出17 int gettop(Stack *p);//获取栈顶18 void push(Stack *p, int key);//插入数据19 void pop(Stack *p);//弹出一个数据20 void show(Stack *p);//显示出来
2.stack.c
1 #include "stack.h" 2 3 void init(Stack *p) 4 { 5 p->top = -1;//代表为空 6 memset(p->data, 0, sizeof(int)*N);//数据清零 7 } 8 9 int isempty(Stack *p)10 {11 if (p->top == -1)12 {13 return 1;//1为空14 }15 else16 {17 return 0;//0不为空18 }19 }20 21 int isfull(Stack *p)22 {23 if (p->top == N - 1)24 {25 return 1;//溢出26 }27 else28 {29 return 0;//没满30 }31 }32 33 int gettop(Stack *p)34 {35 return p->data[p->top];//获取栈顶36 }37 38 void push(Stack *p, int key)39 {40 if (isfull(p) == 1)41 {42 return;43 }44 else45 {46 p->top += 1;47 p->data[p->top] = key;48 }49 }50 51 52 void pop(Stack *p)53 {54 if (isempty(p) == 1)55 {56 return;57 }58 else59 {60 p->top -= 1;61 }62 }63 64 void show(Stack *p)65 {66 if (isempty(p) == 1)67 {68 return;69 }70 else71 {72 printf("\n栈的数据是:\n");73 for (int i = 0; i <= p->top; i++)74 {75 printf("%4d", p->data[i]);//打印栈的数据76 }77 printf("\n");78 }79 }
main.c
1 #include "stack.h" 2 3 void main() 4 { 5 int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; 6 7 Stack mystack; 8 9 init(&mystack);10 11 for (int i = 0; i < 10; i++)12 {13 push(&mystack, a[i]);14 }15 while (!isempty(&mystack))16 {17 printf("%d", gettop(&mystack));18 pop(&mystack);19 }20 21 system("pause");22 }