求高手用栈的操作实现”括号匹配检验“这个程序,用数据结构的知识。谢谢啦!!!

如题所述

这是其中括号匹配的函数部分:
void match(SeqStack S,char *str)//括号的比较
{
int i;
char ch;
for(i = 0; str[i] != '\0'; i++)
{
switch(str[i])
{
case '(':
case '[':
case '{':
Push(&S,str[i]);
break;
case ')':
case ']':
case '}':
if(GetTop(&S)=='#')
{
printf("\n -_-!!! 右括号多余!\n");
exit (0);
}
else
{
ch=GetTop(&S);
if(Compare(ch,str[i]))
Pop(&S);
else
{
printf("\n -_-!!! 对应的左右括号不同类!\n");
exit (0);
}
}
}
}
if(GetTop(&S)=='#')
printf("\n ^_^ 括号匹配! ^_^\n");
else
{
printf("\n -_-!!! 左括号多余!\n");
exit (0);
}
}追问

谢谢啦,我更想要全部的,尤其是GetTop(S,&e),Push(&s,e),Pop(&s,&e)这些部分的实现。

追答

#include
#define Size 200
int exit();
typedef struct node//栈的定义
{
char ch[Size];
int top;
}SeqStack;

void InitStack(SeqStack *S) //构造一个空栈
{
S->top = -1;
}

void Push(SeqStack *S,char x)//进栈操作
{
S->top++;
S->ch[S->top] = x;
}

char Pop(SeqStack *S) //出栈操作
{
char ch;
ch = S->ch[S->top];
S->top--;
return(ch);
}

char GetTop(SeqStack *S)//取栈顶元素
{
char x;
if(S->top == -1)
x = '#';
else
x = S->ch[S->top];
return x;
}
int Match(char ch) //字符优先级基准
{
switch (ch)
{
case '{':
case '}': return 4;
case '[':
case ']': return 5;
case '(':
case ')': return 6;
default:
return 0;
}
}
int Compare(char t,char ch) //字符优先级比较
{
int i,j,x;
i=Match(t);
j=Match(ch);
if(i==j)
x=1;
else
x=0;
return x;
}
void kuohaomatch(SeqStack S,char *str)//括号的比较
{
int i;
char ch;
for(i = 0; str[i] != '\0'; i++)
{
switch(str[i])
{
case '(':
case '[':
case '{':
Push(&S,str[i]);
break;
case ')':
case ']':
case '}':
if(GetTop(&S)=='#')
{
printf("\n -_-!!! 右括号多余!\n");
exit (0);
}
else
{
ch=GetTop(&S);
if(Compare(ch,str[i]))
Pop(&S);
else
{
printf("\n -_-!!! 对应的左右括号不同类!\n");
exit (0);
}
}
}
}
if(GetTop(&S)=='#')
printf("\n ^_^ 括号匹配! ^_^\n");
else
{
printf("\n -_-!!! 左括号多余!\n");
exit (0);
}
}
void main()
{
SeqStack s;
char ch[Size];
InitStack(&s);
printf("请输入:\n");
scanf("%s",ch);
kuohaomatch(s,ch);//括号匹配
}

追问

呵呵呵··谢谢啦。

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答