括号匹配的问题
设表达式以字符形式已存入数组E[n]中,‘#’为表达式的结束符,试写出判断表达式中括号(‘(’和‘)’)是否配对的C语言描述算法:EXYX(E); (注:算法中可调用栈操作的基本算法。) 程序代码:
#include<stdio.h> #include<stdlib.h> //包括malloc()和realloc()函数的头文件 #include<math.h> //包括pow()函数的头文件 #define Max_stack_size 20 #define Addersize 10 typedef char Elemtype; typedef struct{ Elemtype *base; Elemtype *top; int stacksize; }sqStack; void initStack (sqStack *s) { //初始化一个空栈 s->base=(Elemtype *)malloc(Max_stack_size*sizeof(Elemtype)); if(!s->base) exit(0); s->top=s->base; s->stacksize=Max_stack_size; } void pushStack(sqStack *s,Elemtype e){ //入栈操作 if(s->top-s->base>=s->stacksize) { printf("栈已满,追加空间"); s->base=(Elemtype *)realloc(s->base,(s->stacksize+Addersize)*sizeof(Elemtype)); if(!s->base) exit(0); s->top=s->base+s->stacksize; s->stacksize=s->stacksize+Addersize;} *(s->top)=e; s->top++; } void popStack(sqStack *s,Elemtype *e){ //出栈操作 if(s->top==s->base) exit(0); *e=*--(s->top); } void clearStack(sqStack *s) //清空栈 { s->top=s->base; } void destroyStack(sqStack *s) { //销毁栈 int i; int len; len=s->stacksize; for(i=0;i<len;i++) { free(s->base); s->base++; } s->base=NULL; s->top=s->base; s->stacksize=0; } int EXXX(sqStack *s,int n) { char x; int i=0; int j; char E[n]; for(j=0;j<n;j++) { printf("输入第%d个数据:",j+1); scanf("%c",&E[j]); getchar(); } pushStack(s,'#'); while(E[i]!='#') { printf("1 "); switch(E[i]) { case '(':pushStack(s,'(');i++;break; case ')':if(*(s->top-1)=='(') { popStack(s,&x);i++;break; } else { printf("不匹配");exit(0); } case '#':if(*(s->top-1)=='#') { printf("匹配\n");break; } else{ printf("不匹配\n");exit(0); } default :i++; } } } int main() { int n; sqStack s; initStack(&s); printf("initial:\n"); printf("输入n的值:\n"); scanf("%d",&n); EXXX(&s,n); }结果不对 请高手检查一下