zoukankan      html  css  js  c++  java
  • 栈的应用--栈用作判断平衡符号,[()]对的,[(])错的

    #include<stdio.h>
    #include<stdlib.h>
    struct Node;
    typedef struct Node *PtrToNode;
    typedef PtrToNode Stack;
    
    struct Node{
        char Ele;
        PtrToNode Next;
    };
    
    Stack
    CreateStack( void )
    {
        Stack S;
        S = malloc( sizeof( struct Node ) );
        if(S == NULL )
            printf("out of space");
        S->Next = NULL;
        return S;
    }
    void
    Push(char ch,Stack S)
    {
        PtrToNode TmpCell;
        TmpCell = malloc(sizeof( struct Node ));
        if(TmpCell == NULL)
            printf("out of space ");
        else
        {
            TmpCell->Next = S->Next;
            S->Next = TmpCell;
            TmpCell->Ele = ch;
        }
    }
    int
    IsEmpty(Stack S)
    {
        return S->Next == NULL;
    }
    void
    Pop( Stack S )
    {
        PtrToNode TmpCell;
        TmpCell = S->Next;
        S->Next = TmpCell->Next;
        free(TmpCell);
    }
    char
    Top( Stack S )
    {
        return S->Next->Ele;
    }
    
    int main()
    {
        char Tmp;
        Stack S;
        S = CreateStack();
        while( ( Tmp = getchar() ) != '
    ' )
        {
            if(Tmp == '[' || Tmp == '(')
                Push(Tmp,S);
            else if(Tmp == ']')
            {
                if( !IsEmpty( S ) )
                {
                    char tmp;
                    tmp = Top( S );
                    Pop( S );
                    if(tmp != '[')
                        printf("error");
                }
                else
                    printf("Error");
            }//else if
            else
            {
                if( !IsEmpty( S ) )
                {
                    char tmp;
                    tmp = Top( S );
                    Pop( S );
                    if(tmp != '(')
                        printf("error");
                }
                else
                    printf("error");
            }//else
        }
        if( !IsEmpty( S ))
            printf("error");
        return 0;
    }
    View Code

    算法描述:如果遇到开放符号就进栈,如果遇到封闭符号,先判断此时是不是空栈,是就报错,否则,就出栈判断是否是其对应的开放符号,不是就报错,如果读到文件结尾,栈不为空,报错

  • 相关阅读:
    c#操作ElasticSearch5详解
    消息推送服务
    Elasticsearch5.0.1 + Kibana5.0.1 + IK 5.0.1
    C#使用ES
    C# 开发人员的函数式编程
    Swagger文档转Word
    Spring Security OAuth2 Demo -- good
    is not eligible for getting processed by all BeanPostProcessors
    成功都一样,失败各不同;失败的项目也许值得你警醒
    java.exe进程来源排查录
  • 原文地址:https://www.cnblogs.com/gabygoole/p/4616033.html
Copyright © 2011-2022 走看看