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 != '\n' )
    {
        if ( input == '(' || input == '{' || input == '[' )
            Push(input);
        else if ( input == ')' )
        {
            if( IsEmpty() || TopItem() != '(' )
            {
                printf("This sequence is not balance!\n");
                return 0;
            }
            else
                Pop();
        }

        else if ( input == ']' )
        {
            if( IsEmpty() || TopItem() != '[' )
            {
                printf("This sequence is not balance!\n");
                return 0;
            }
            else
                Pop();
        }

        else if ( input == '}' )
        {
            if( IsEmpty() || TopItem() != '{' )
            {
                printf("This sequence is not balance!\n");
                return 0;
            }
            else
                Pop();
        }

        scanf("%c", &input);
    }

    if ( IsEmpty() )
        printf("Balanced!\n");
    else
        printf("Not Balance!\n");

    return 0;
}
View Code

 

posted @ 2017-11-29 13:16  Veritas_des_Liberty  阅读(368)  评论(0编辑  收藏  举报