Stack栈——getMin()
Posted ai-cobe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Stack栈——getMin()相关的知识,希望对你有一定的参考价值。
获取栈——stack中最小的元素
- 建立另一个栈——temp
- 如果两个栈都为空,则将node同时push两个栈中
- 接着插入new_node,如果temp不为空,则比较栈顶node->data和new_node->data。
- 如果node->data大于new_node->data,则将new_node同时push两个栈中
- 反之,只push进stack栈中
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 struct stack 5 { 6 int data; 7 struct stack * next; 8 }; 9 struct stack * newNode(int data) 10 { 11 struct stack * new_node = (struct stack *)malloc(sizeof(struct stack)); 12 new_node->data = data; 13 new_node->next = NULL; 14 } 15 void push(struct stack ** root, int data) 16 { 17 struct stack * new_node = newNode(data); 18 19 new_node->next = (*root); 20 (*root) = new_node; 21 printf(" %-2d pushed to stack", data); 22 } 23 int isEmpty(struct stack * root) 24 { 25 return NULL == root ? 1 : 0; 26 } 27 int pop(struct stack ** root) 28 { 29 if(isEmpty((*root))) 30 { 31 printf(" Empty!"); 32 return 0; 33 } 34 struct stack * temp = (*root); 35 int num = temp->data; 36 (*root) = temp->next; 37 free(temp); 38 39 return num; 40 } 41 void push_new(struct stack ** root, struct stack ** other, int data) 42 { 43 if(NULL == (*root) || NULL == (*other)) 44 { 45 push(root, data); 46 push(other, data); 47 } 48 else if(data < ((*other)->data)) 49 { 50 printf(" %-2d poped off", pop(other)); 51 push(other, data); 52 push(root, data); 53 }else if(data > ((*other)->data)) 54 { 55 push(root, data); 56 } 57 } 58 int getMin(struct stack * other) 59 { 60 return other->data; 61 } 62 int main(void) 63 { 64 struct stack * root = NULL; 65 struct stack * other = NULL; 66 67 push_new(&root, &other, -5); 68 push_new(&root, &other, 1); 69 push_new(&root, &other, 8); 70 push_new(&root, &other, 0); 71 push_new(&root, &other, -1); 72 push_new(&root, &other, -7); 73 74 printf(" MIN = %d", getMin(other)); 75 return 0; 76 }
以上是关于Stack栈——getMin()的主要内容,如果未能解决你的问题,请参考以下文章