您的位置:首页 > 编程语言 > C语言/C++

用堆栈解决括号匹配问题(C语言)

2013-11-13 13:05 483 查看
#include<stdio.h>

#include<stdlib.h>

int main()

{

void BracketMatch();

BracketMatch();

}

typedef char ElemType;

typedef struct Stack

{

int top;

int MaxSize;

ElemType *stack;

}Stack;

void Creat(Stack*s , int m)

{

if(m<0)

{

printf("%d is
negtive!",m);

return;

}

s->top=-1;

s->MaxSize=m;

s->stack=(ElemType*)malloc(sizeof(ElemType)*m);

}//Creat a stack

void Push(Stack *s, ElemType data)

{

if(s->top==s->MaxSize-1)

{

printf("The stack is
full!");

return;

}

s->top++;

s->stack[s->top]=data;

}//Push data in the stack s

ElemType Pop(Stack *s)

{

ElemType temp;

if(
s->top<-1)

{

printf("The stack is
NULL!");

return;

}

temp=s->stack[s->top];

s->top--;

return temp;

}//Pop the top element of the stack

void BracketMatch()

{

int n=20;

int i=0;

char str
;

char ch;

printf("请输入一个算术表达式(%d字符以内)\n",n);

scanf("%s",str);

Stack *s=(Stack*)malloc(sizeof(Stack));

Creat(s,n);//creat a stack of n elements

while(str[i]!='\0')

{

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

Push(s,str[i]);

if(str[i]==')')

{

ch=Pop(s);

if(ch!='(')

{
printf("Match
failure!\n");return; }

}

if(str[i]==']')

{

ch=Pop(s);

if(ch!='[')

{
printf("Match
failure!\n");return; }

}

if(str[i]=='}')

{

ch=Pop(s);

if(ch!='{')

{
printf("Match
failure!\n");return; }

}

i++;

}

if(s->top==-1) //最后堆栈有无元素判断

printf("Match
Successfully!\n");

else

printf("Match
failure!\n");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: