zoukankan      html  css  js  c++  java
  • 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("
    %-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 }
  • 相关阅读:
    配置对即时负载的优化
    通过重组索引提高性能
    使用索引视图提高性能
    sqlcmd
    (转)使用SQLCMD在SQLServer执行多个脚本
    在SQLServer处理中的一些问题及解决方法 NEWSEQUENTIALID()
    java反射机制与动态代理
    天天用的开发环境,你真的了解吗?
    通过IP获取对应所在地的地址
    unity3d KeyCode各键值说明
  • 原文地址:https://www.cnblogs.com/AI-Cobe/p/9358702.html
Copyright © 2011-2022 走看看