zoukankan      html  css  js  c++  java
  • Balance(Stack)

    栈的运用

    mooc视频连接

    #include <iostream>
    
    using namespace std;
    
    char S[100];
    int Top, Number_of_Items = 0;
    
    void Push(char c)
    {
        if ( Number_of_Items == 0 )
        {
            Top = 0;
            S[0] = c;
        }
    
        else
        {
            Top++;
            S[Top] = c;
        }
    
        Number_of_Items++;
    }
    
    void Pop()
    {
        Top--;
        Number_of_Items--;
    }
    
    char TopItem()
    {
        return S[Top];
    }
    
    int IsEmpty()
    {
        if ( Number_of_Items == 0 )
            return 1;
        else
            return 0;
    }
    
    int main()
    {
        char input;
    
        printf("Enter a paretheses sequence (type <Enter> when done) : ");
    
        /*solve problem*/
    
        scanf("%c", &input);
    
        while ( input != '
    ' )
        {
            if ( input == '(' || input == '{' || input == '[' )
                Push(input);
            else if ( input == ')' )
            {
                if( IsEmpty() || TopItem() != '(' )
                {
                    printf("This sequence is not balance!
    ");
                    return 0;
                }
                else
                    Pop();
            }
    
            else if ( input == ']' )
            {
                if( IsEmpty() || TopItem() != '[' )
                {
                    printf("This sequence is not balance!
    ");
                    return 0;
                }
                else
                    Pop();
            }
    
            else if ( input == '}' )
            {
                if( IsEmpty() || TopItem() != '{' )
                {
                    printf("This sequence is not balance!
    ");
                    return 0;
                }
                else
                    Pop();
            }
    
            scanf("%c", &input);
        }
    
        if ( IsEmpty() )
            printf("Balanced!
    ");
        else
            printf("Not Balance!
    ");
    
        return 0;
    }
    View Code
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    畅通工程续 dijkstra
    能量项链 区间dp
    机器人军团
    skiing
    数论知识
    灯泡游戏
    60. 第k个排列
    17. 电话号码的字母组合
    101. 对称二叉树
    144. 二叉树的前序遍历
  • 原文地址:https://www.cnblogs.com/h-hkai/p/7919896.html
Copyright © 2011-2022 走看看