动态栈-------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 enum return_result {EMPTY_OK = 100, EMPTY_NO, PUSH_OK, PUSH_NO, POP_OK, POP_NO}; 12 13 typedef struct node 14 { 15 int data; 16 struct node * next; 17 }Node, *Link;//链结构 18 19 typedef struct stk 20 { 21 Link space; 22 }Stack;//栈结构 23 24 /*malloc是否正确执行*/ 25 void is_malloc_ok(void * node) 26 { 27 if (node == NULL) 28 { 29 printf("malloc error!\n"); 30 exit(-1); 31 } 32 } 33 34 /*创建一个栈*/ 35 void create_stack(Stack ** stack) 36 { 37 *stack = (Stack *)malloc(sizeof(Stack)); 38 is_malloc_ok(*stack); 39 (*stack)->space = (Link)malloc(sizeof(Node)); 40 is_malloc_ok((*stack)->space); 41 } 42 43 /*初始化栈*/ 44 void init_stack(Stack *stack) 45 { 46 stack->space->next = NULL; 47 } 48 49 /*创建一个压栈元素*/ 50 void create_node(Link * new_node) 51 { 52 *new_node = (Link)malloc(sizeof(Node)); 53 is_malloc_ok(*new_node); 54 } 55 56 /*压栈*/ 57 void push_stack(Stack *stack, Link new_node) 58 { 59 new_node->next = stack->space->next; 60 stack->space->next = new_node; 61 } 62 63 /*判断栈空*/ 64 int is_stack_empty(Stack *stack) 65 { 66 Link p = NULL; 67 68 p = stack->space->next; 69 70 if (p == NULL) 71 { 72 return EMPTY_OK; 73 } 74 75 return EMPTY_NO; 76 } 77 78 /*出栈*/ 79 int pop_stack(Stack *stack) 80 { 81 Link p = NULL; 82 int data; 83 84 if (stack == NULL) 85 {//栈不存在 86 printf("stack is not exist!\n"); 87 exit(-1); 88 } 89 90 if (EMPTY_OK == is_stack_empty(stack)) 91 { 92 printf("stack is empty!\n"); 93 return POP_NO; 94 } 95 p = stack->space->next; 96 stack->space->next = p->next; 97 98 data = p->data; 99 100 free(p);//释放栈顶 101 102 return data; 103 } 104 105 /**/ 106 void release_stack(Stack **stack) 107 { 108 Link p = NULL; 109 110 if (EMPTY_NO == is_stack_empty(*stack)) 111 {//栈不空 112 p = (*stack)->space->next; 113 114 while ((*stack)->space->next != NULL) 115 { 116 (*stack)->space->next = p->next; 117 free(p); 118 p = (*stack)->space->next; 119 } 120 } 121 free((*stack)->space);//链头结点 122 free(*stack);//释放栈 123 *stack = NULL; 124 } 125 126 int main() 127 { 128 int i; 129 int ret; 130 Stack *stack = NULL; 131 Link new_node = NULL;//入栈新元素 132 133 create_stack(&stack); 134 135 init_stack(stack); 136 137 for (i = 0; i < 10; i++) 138 {//入栈 139 create_node(&new_node); 140 new_node->data = i + 1; 141 push_stack(stack, new_node);//相当于链表的头插 142 } 143 144 for (i = 0; i < 5; i++) 145 {//出栈 146 ret = pop_stack(stack); 147 148 if (ret == POP_NO) 149 { 150 break; 151 } 152 printf("%d\n", ret); 153 } 154 155 release_stack(&stack); 156 pop_stack(stack); 157 return 0; 158 }