静态栈-------C语言
1 /***************************************************** 2 Author:Simon_Kly Version:0.1 Date: 20170520 3 Description:静态栈 4 Mail: degaullekong@gmail.com 5 Funcion List: 6 *****************************************************/ 7 8 #include <stdio.h> 9 #include <stdlib.h> 10 11 12 #define SIZE 10 13 14 enum result {FULL_OK = 100, FULL_NO, EMPTY_OK, EMPTY_NO, PUSH_OK, PUSH_NO, POP_OK, POP_NO}; 15 16 typedef struct stack_node 17 { 18 int data[SIZE]; 19 int top; 20 }Stack; 21 22 /*创建栈*/ 23 void create_stack(Stack ** stack) 24 { 25 *stack = (Stack *)malloc(sizeof(Stack)); 26 if (NULL == *stack) 27 { 28 printf("malloc error!\n"); 29 exit(-1); 30 } 31 32 (*stack)->top = -1; 33 } 34 35 /*初始化栈*/ 36 void init_stack(Stack *stack) 37 { 38 stack->top = -1; 39 } 40 41 /*判断栈是否满*/ 42 int is_stack_full(Stack *stack) 43 { 44 if (stack->top == SIZE - 1)//栈已满 45 { 46 return FULL_OK; 47 } 48 49 return FULL_NO;//栈不满 50 } 51 /*压栈*/ 52 void push_stack(Stack *stack, int data) 53 { 54 if (FULL_OK == is_stack_full(stack)) 55 { 56 printf("stack is full!\n"); 57 return ; 58 } 59 else 60 { 61 stack->top++; 62 stack->data[stack->top] = data; 63 } 64 } 65 66 /*判断栈是否空*/ 67 int is_stack_empty(Stack *stack) 68 { 69 if (-1 == stack->top) 70 { 71 return EMPTY_OK;//栈空 72 } 73 74 return EMPTY_NO;//不为空 75 } 76 77 /*出栈*/ 78 int pop_stack(Stack *stack) 79 { 80 if (EMPTY_OK == is_stack_empty(stack)) 81 { 82 printf("stack is empty!\n"); 83 return POP_NO; 84 } 85 else 86 { 87 return stack->data[stack->top--]; 88 } 89 } 90 91 /*读栈顶*/ 92 void read_stack_top(Stack *stack) 93 { 94 if (EMPTY_OK == is_stack_empty(stack))//判断栈是否空 95 { 96 printf("stack is empty!\n"); 97 return ; 98 } 99 100 printf("stack top is %d\n", stack->data[stack->top]); 101 102 } 103 104 int main() 105 { 106 Stack *stack; 107 int i; 108 int ret; 109 110 create_stack(&stack); 111 init_stack(stack);//栈的初始化 112 113 //进栈 114 for (i = 0; i < SIZE; i++) 115 { 116 push_stack(stack, i + 1); 117 } 118 //出栈 119 for (i = 0; i < SIZE; i++) 120 { 121 read_stack_top(stack); 122 ret = pop_stack(stack); 123 124 if (ret == POP_NO) 125 { 126 break; 127 } 128 printf("%d\n", ret); 129 } 130 putchar(10); 131 132 read_stack_top(stack); 133 134 free(stack); 135 return 0; 136 }