7-5 parenthesis.c
1 #include <stdio.h> 2 #define MAXLENGTH 80 //最大字符串长度 3 #define STACK_INIT_SIZE 100 4 #define SIZE_INCREMENT 5 5 typedef struct //栈结构 6 { 7 int *base; //栈底 8 int *top; //栈顶 9 int stacksize; //栈大小 10 }SqStack,*SQSTACK; 11 int StackInit(SQSTACK s) //初始化栈 12 { 13 s->base=(int *)malloc(STACK_INIT_SIZE*sizeof(int)); 14 if(!(s->base)) 15 exit(0); 16 s->top=s->base; 17 s->stacksize=STACK_INIT_SIZE; 18 return 1; 19 } 20 int PUSH(SQSTACK s,int e) //入栈 21 { 22 if(s->base+s->stacksize==s->top) 23 { 24 s->base=(int *)realloc(s->base,(SIZE_INCREMENT+s->stacksize)*sizeof(int)); 25 s->top=s->base+s->stacksize; 26 s->stacksize+=SIZE_INCREMENT; 27 } 28 *(s->top)=e; 29 s->top+=1; 30 return 1; 31 } 32 int POP(SQSTACK s,int *p) //出栈 33 { 34 if(s->base==s->top) //空栈 35 return 0; 36 *p=*(s->top-1); 37 s->top--; 38 return 1; 39 } 40 int StackLength(SQSTACK s) //栈的长度(元素数量) 41 { 42 return (s->top-s->base); 43 } 44 int StackFree(SQSTACK s) //释放栈 45 { 46 free(s->base); 47 s->top=s->base=NULL; 48 return 1; 49 } 50 51 void ParenthesisMatch(char *expr) 52 { 53 SqStack s; 54 int i,len,no; 55 if(!StackInit(&s)) //初始化栈失败 56 exit(0);//退出 57 len=strlen(expr); //取字符串长度 58 for(i=1;i<=len;i++) 59 { 60 if(expr[i-1]==‘(‘) 61 PUSH(&s,i); //左插号位置序号入栈 62 else if(expr[i-1]==‘)‘) 63 { 64 if(POP(&s,&no)) 65 printf("括号配对:%d -- %d\n", no,i); 66 else 67 printf("没有左括号与位于第%d个位置的右侧号配对!\n",i); 68 } 69 } 70 while(StackLength(&s)>0) //若栈中还有数据,表示还有左括号没配对 71 { 72 POP(&s,&no); 73 printf("位于第%d位置的左括号没有配对的右括号!\n", no); 74 } 75 StackFree(&s); //释放栈 76 } 77 int main() 78 { 79 char expr[MAXLENGTH]; 80 printf("输入一个带括号的表达式(长度不超过%d个字符):\n",MAXLENGTH); 81 scanf("%s",expr); 82 ParenthesisMatch(expr); 83 84 getch(); 85 return 0; 86 }
时间: 2024-10-24 05:14:20