求高手用栈的操作实现”括号匹配检验“这个程序,用数据结构的知识.谢谢啦!
- 提问者网友:动次大次蹦擦擦
- 2021-05-20 12:04
- 五星知识达人网友:慢性怪人
- 2021-05-20 12:24
这是其中括号匹配的函数部分:
void match(SeqStack S,char *str)//括号的比较
{
\x05int i;
\x05char ch;
\x05for(i = 0; str[i] != '\0'; i++)
\x05{
\x05\x05switch(str[i])
\x05\x05{
\x05\x05case '(':
\x05\x05case '[':
\x05\x05case '{':
\x05\x05\x05Push(&S,str[i]);
\x05\x05\x05break;
\x05\x05case ')':
\x05\x05case ']':
\x05\x05case '}':
\x05\x05\x05if(GetTop(&S)=='#')
\x05\x05\x05{
\x05\x05\x05\x05printf(\n -_-!右括号多余!\n);
\x05\x05\x05\x05exit (0);
\x05\x05\x05}
\x05\x05\x05else
\x05\x05\x05{
\x05\x05\x05\x05ch=GetTop(&S);
\x05\x05\x05\x05if(Compare(ch,str[i]))
\x05\x05\x05\x05\x05Pop(&S);
\x05\x05\x05\x05else
\x05\x05\x05\x05{
\x05\x05\x05\x05\x05printf(\n -_-!对应的左右括号不同类!\n);
\x05\x05\x05\x05\x05exit (0);
\x05\x05\x05\x05}
\x05\x05\x05}
\x05\x05}
\x05}
\x05if(GetTop(&S)=='#')
\x05\x05printf(\n 括号匹配!^_^\n);
\x05else
\x05{
\x05\x05printf(\n -_-!左括号多余!\n);
\x05\x05exit (0);
\x05}
}
再问: 谢谢啦,我更想要全部的,尤其是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);//括号匹配 }
再问: 呵呵呵··谢谢啦。