zoukankan      html  css  js  c++  java
  • 实用栈检查括号是否匹配

    设字符串仅由圆括号“(”和“)”,方括号“[”和“]”,花括号“{”和“}”组成,利用链栈的操作编写一个检查括号是否正确配对的算法:int Matcher(LstackTP *ls)。例如[{{()}[ ]}(){[ ]}]是正确的,而{{()[ ]}}]}则不正确。设链栈定义如下:(6分)

    typedef struct node

    {   char data;

    struct node * next;

    } LStackTp

    // Stack.cpp : Defines the entry point for the console application.
    //

    #include "stdafx.h"
    #include "stdlib.h"


    typedef struct node
    {
        char data;
        struct  node * next;
    }LStackTp;


    void InitStack(LStackTp **ls)
    {
        *ls=NULL;
    }

    void Push(LStackTp **ls,char x)
    {
        LStackTp *p;
        p=(LStackTp *)malloc(sizeof(LStackTp));

        p->data=x;
        p->next=*ls;
        *ls=p;
    }

    int Pop(LStackTp **ls,char *x)
    {
        LStackTp *p;
        if (*ls!=NULL)
        {
            p=*ls;
            *x=p->data;
            *ls=p->next;
            free(p);
            return 1;
        
        }

            return 0;
    }

    int EmptyStack(LStackTp *ls)
    {
        return (ls==NULL);
    }


    char GetStackTop(LStackTp *ls)
    {

        if (ls)
            return ls->data;
        else
            return '\0';
    }


    void PrintStack(LStackTp **ls)
    {
            LStackTp *p;
            p=*ls;

            while (p)
            {
                printf("%c \n",p->data);
                p=p->next;    
            
            }

    }



    int MyMatcher(char ch1,char ch2)
    {
        if ((ch1=='(') && (ch2==')')) return 1;
        if ((ch1=='[') && (ch2==']')) return 1;
        if ((ch1=='{') && (ch2=='}')) return 1;
        return 0;
    }


    int Matcher(LStackTp **ls,char *p)
    {
        char ch;
        char *x=&ch;
        while (*p)
        {
            if ( MyMatcher(GetStackTop(*ls),(*p) ))
            {        
                Pop(ls,x);            
            }
            else
            {
                Push(ls,*p);
            }        
                p++;    
        }
        return EmptyStack(*ls);
    }



    int main(int argc, char* argv[])
    {

        LStackTp *S;
        InitStack(&S);

        char *p="(()){}[]{{}({})}({[()]})";

        if (Matcher(&S,p))
            printf("这是一个合法的括号序列!");
        else
            printf("这是一个不合法的括号序列!");


        printf("\n\n\n\n\n");
        return 0;

    } 

  • 相关阅读:
    ASP.NET 2.0 用户注册控件的密码验证问题
    编程使用GridView,DataList的模版列
    在您的站点上添加 Windows Live Favourites 收藏入口
    推荐个很好玩的开源项目Ascii Generator dotNET
    Castle ActiveRecord 在Web项目和WinForm项目中
    HTML解析器项目进展和新的构思
    SilverLight 的跨域跨域访问
    SQL 语句之Join复习
    【笔记】提高中文分词准确性和效率的方法
    ASP.NET 动态加载控件激发事件的问题
  • 原文地址:https://www.cnblogs.com/lance2088/p/2192726.html
Copyright © 2011-2022 走看看