2014-11-04 46 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,那麼你知道所有的圓括號均衡。如果是肯定的,那麼你缺少或者有不平衡的右括號。