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 }