加载中…
个人资料
XiaoWanDuo
XiaoWanDuo
  • 博客等级:
  • 博客积分:0
  • 博客访问:759
  • 关注人气:33
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

括号匹配检验(C语言、顺序栈应用)

(2012-07-25 17:04:00)
标签:

杂谈

    编写程序,检验括号配对的匹配是否正确。假设表达式中只有两种括号,‘(’和‘],嵌套顺序任意,即([})或者[()]为正确的表达式。该程序也运用了栈的思想。若是左括号则入栈,若是右括号则看是否和当前栈顶元素是否匹配。若是则Pop(),不是则当前表达式括号不匹配。代码详见下。主要是看Bracket()函数。其他则是栈的基本操作。

#include <stdio.h>

#include <malloc.h>

#define STACK_SIZE 200

#define   EleType  char

//栈的节点声明

typedef struct Stack{

    EleType top;

    EleType array[STACK_SIZE];

    }Stack,*pStack;

//初始化一个空栈

int Init_Stack(pStack S){

    S->top 0;//top0表示空栈

    return 1;

    }

//测试是否为空栈

int IsEmpty(pStack S){

    if(S->top==0)return 1;

       else return 0;

    }

//元素e入栈

int Push(pStack S,EleType e){

    S->top++;

    S->array[S->top] e;

    return S->top;

    }

//出栈,并返回该元素值

EleType Pop(pStack S){

    S->top--;

    return S->array[S->top+1];

    }

//括号匹配函数

int Bracket(pStack S,char a[],int length){

     int i=0;

     for(;i<length;i++){

        if(a[i]==']'||a[i]==')'){

            switch(a[i]){

               case ')': if('('!=Pop(S)){Error();};break;

               case ']': if('['!=Pop(S)){Error();};break;

               default:printf("Error!");break;

                }

            }else{

                if((a[i]=='(')||(a[i]=='[')){

                 Push(S,a[i]);

                 }

                 else{Error();}

                }

        }

    if(IsEmpty(S)){

        printf("ok!");

        return 1;

        }

       else{

           printf("failed");

           return 0;}

    }

int Error(){

    printf("Error");getch();exit(-1);

    }

void main(){

    pStack S;

 

    char a[]="[([][])]";

    (pStack)malloc(sizeof(Stack));

    Init_Stack(S);

    Bracket(S,a,8);

    getch();

    }

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有