码迷,mamicode.com
首页 > 其他好文 > 详细

Stack栈——getMin()

时间:2018-07-24 11:14:43      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:off   roo   pre   两个栈   stack   sem   next   void   \n   

获取栈——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 }

 

Stack栈——getMin()

标签:off   roo   pre   两个栈   stack   sem   next   void   \n   

原文地址:https://www.cnblogs.com/AI-Cobe/p/9358702.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!