-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;
}
`
你的'pop()'函數看起來不對。 'return'後面的語句都不會被執行。 – 2014-11-04 16:41:16