74

判断一组括号是否匹配(用栈)

 5 years ago
source link: http://www.10tiao.com/html/461/201806/2650716503/2.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#include <stdio.h>

#define Stack_Size 100

typedef int StackElemType;

//定义栈的结构体 

typedef struct

{

StackElemType elem[Stack_Size];

int top;

}SeqStack;

//声明函数 

void InitStack(SeqStack *s);

void Push(SeqStack *s,StackElemType x);

int Pop(SeqStack *s);

int IsEmpty(SeqStack *s);

int GetTop(SeqStack *s);

void BracketMatch(char *str);

int Match(char left,char right);

int main()

{

char str[]={"]{[]}]"};//定义字符串 

BracketMatch(&str[0]);//传首地址 BracketMatch(str)

return 0;

}

//初始化栈 

void InitStack(SeqStack *s)

{

s->top=-1;

}

//进栈 

void Push(SeqStack *s,StackElemType x)

{

if(s->top==Stack_Size)

printf("栈已满\n");

else


s->top++;

s->elem[s->top]=x;

 }

}

//出栈 

int Pop(SeqStack *s)

{

int a;

a=s->elem[s->top];

s->top--;

return a; 

}

//判空 

int IsEmpty(SeqStack *s)

{

if(s->top==-1)

return 1;

else

return 0; 

}

//获取栈顶元素 

int GetTop(SeqStack *s)

{

return s->elem[s->top];

}

//看左右括号是否匹配 

int Match(char left,char right)

{

switch(left)

{

case '[':

left=']';

break;

case '{':

left='}';

break;

case '(':

       left=')';

break;

default:

printf("输入错误\n");

break; 

}

if(left==right)

return 1;

else

return 0; 



//括号匹配函数  在该函数中定义栈,这样操作更简单 

void BracketMatch(char *str)

{

SeqStack S;

int i;

//char ch;

InitStack(&S);

for(i=0;str[i]!='\0';i++)

{

switch(str[i])

{

case '(':

case '{':

case '[':

Push(&S,str[i]);

break;

case ')':

case '}':

case ']':

if(IsEmpty(&S))

{

printf("右括号多余\n");

return ;

}

else

{

int top;

top=GetTop(&S);

if(Match(top,str[i]))

printf("%c",Pop(&S));//

else

{

printf("\n对应的左右括号不同类!");

return ;

}




}

}

if(IsEmpty(&S))

printf("\n括号匹配!");

else

printf("\n左括号多余");  

}





About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK