Stack栈——getMin()

获取栈——stack中最小的元素

  1. 建立另一个栈——temp
  2. 如果两个栈都为空,则将node同时push两个栈中
  3. 接着插入new_node,如果temp不为空,则比较栈顶node->data和new_node->data。
  4. 如果node->data大于new_node->data,则将new_node同时push两个栈中
  5. 反之,只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("\n%-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("\nEmpty!");
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("\n%-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("\nMIN = %d", getMin(other));
75     return 0;
76 }

 

posted @ 2018-07-24 10:43  一凡夫一俗子  阅读(141)  评论(0编辑  收藏  举报