2014-11-04 104 views
-1

我尝试使用平衡括号算法使用堆栈中的CI已正确计算出当果酱是相同的方式(例如“()”或“{}”或“[]”),但当他们混合然后我得到错误的答案使用堆栈平衡的Parantheses

我的代码中的错误是什么?

int count=0; typedef struct node{ struct node *next; char data; }node; node *top; node *local; node *temp; void create(){ top=NULL; } void push(char data){ if(top==NULL){ top=malloc(sizeof(node)); top->next=NULL; top->data=data; } else{ temp=malloc(sizeof(node)); temp->data=data; temp->next=top; top=temp; } count++; } char pop(){ local=top; if(local==NULL){ printf("Empty stack\n"); return; } else{ local=local->next; } //printf("%d\n",top->data); return top->data; free(top); top=local; count--; } int empty() { return top==NULL; } int match(char a,char b) { if(a=='[' && b==']') return 1; if(a=='{' && b=='}') return 1; if(a=='(' && b==')') return 1; return 0; }/*End of match()*/ int main() { int no, ch, e; char str[51]; scanf("%s",str); int z; int i; char temp; int balanced=1; z=strlen(str); for(i=0;i<z;i++) { if(str[i]=='(' || str[i]=='{' || str[i]=='[') push(str[i]); else if(str[i]==')' || str[i]=='}' || str[i]==']') {temp=pop(); if(empty) balanced=0; if(!match(str[i],temp)) balanced=0; else balanced=1; } } printf("%d\n",balanced); return 0; }

`

+1

你的'pop()'函数看起来不对。 'return'后面的语句都不会被执行。 – 2014-11-04 16:41:16

回答

2

忽略你的栈代码在你pop()功能问题和休息,我会做平衡algorithim这样的:

int balanced = 0; 

for(i = 0; i < strlen(str); ++i) 
{ 
    if(str[i]=='(' || str[i]=='{' || str[i]=='[') 
    { 
     push(str[i]); 
     ++balanced; 
    } 
    else if(str[i]==')' || str[i]=='}' || str[i]==']') 
    { 
     temp = pop(); 
     if (match(str[i], temp)) --balanced; 
    } 
} 

printf("%d\n", balanced); 

如果balanced末为0,那么你知道所有的圆括号均衡。如果是肯定的,那么你缺少或者有不平衡的右括号。