1 #include <stdio.h> 2 #include <stdlib.h> 3 /*min函數的棧,可去棧最小值,pup,push,min時間複雜度爲o(1)*/ 4 /* 5 * 分析,程序通常都是空間換時間,除了很是好的算法。 6 * 因此能夠弄2個棧解決問題。 7 * 下面是鏈表實現的棧,簡單點的用靜態動態數組。 8 * 寫的比較亂,由於從原來棧程序改的,只是表示一種思路, 9 * 沒有根據題目編寫 10 */ 11 typedef struct stack_node{ 12 int value; 13 struct stack_node *next; 14 }stack_node; 15 16 static stack_node *stack, *stack_min; 17 static int value_min; 18 //is_full() create_stack() destroy_stack() 19 int is_empty(stack_node *node) 20 { 21 return node == NULL; 22 } 23 24 void push(stack_node **node, int value) 25 { 26 stack_node *new_node; 27 28 new_node = malloc(sizeof(stack_node)); 29 if(new_node == NULL){ 30 perror("malloc failure:"); 31 return; 32 } 33 new_node->value = value; 34 new_node->next = *node; 35 *node = new_node; 36 } 37 /*只是彈出棧,但不返回,無反作用的函數*/ 38 void pop(stack_node **node) 39 { 40 stack_node *first_node; 41 42 if(is_empty(*node)){ 43 printf("stack is empty.\n"); 44 return; 45 } 46 first_node = *node; 47 *node = first_node->next; 48 free(first_node); 49 } 50 /*只取值不銷燬*/ 51 int top(stack_node *node) 52 { 53 if(is_empty(node)){ 54 printf("stack is empty.\n"); 55 exit(0); 56 } 57 return node->value; 58 } 59 60 void destroy_node(stack_node **node) 61 { 62 while(!is_empty(*node)) 63 pop(node); 64 } 65 void push_min(int value) 66 { 67 if(is_empty(stack_min)) 68 value_min = value; 69 if(value < value_min) 70 value_min = value; 71 72 push(&stack_min, value_min); 73 push(&stack, value); 74 } 75 void pop_min(void) 76 { 77 pop(&stack_min); 78 pop(&stack); 79 } 80 int min(void) 81 { 82 return top(stack_min); 83 } 84 int main() 85 { 86 push_min(3); 87 push_min(4); 88 push_min(3); 89 push_min(2); 90 push_min(5); 91 push_min(1); 92 93 printf("%d, %d\n", top(stack), min()); 94 pop_min(); 95 printf("%d, %d\n", top(stack), min()); 96 pop_min(); 97 printf("%d, %d\n", top(stack), min()); 98 return 0; 99 }