【发布时间】:2020-11-23 19:11:46
【问题描述】:
我正在尝试编写一个程序,在其中我使用数组实现堆栈并使用它们来检查给定字符串是否具有平衡括号。
例如。如果输入 '(()){}[()]' ,程序会输出 'Balanced',否则如果输入 '({})[' 程序会输出 'Notbalanced'。
这部分是栈的数组实现。
#include <stdio.h>
#include <stdlib.h>
#define MAX 50
int stack[MAX];
int top=-1;
void push(char val){
if(top==MAX-1){
printf("stack is already full,error\n");
}else{
top++;
stack[top]=val;
}
}
char pop(){
if(top==-1){
printf("not enough elements,error\n");
exit(1);
}else{
top--;
return stack[top];
}
}
这部分是解决问题的常用方法的实现。
int isMatching(char c1, char c2){
if(c1=='{' && c2=='}')
return 1;
else if(c1 =='(' && c2==')')
return 1;
else if(c1=='[' && c2==']')
return 1;
return 0;
}
int isBalanced(char str[]){
int i=0;
while(str[i]!='\0'){
if(str[i]=='{' || str[i]=='[' || str[i]=='('){
push(str[i]);
}
if(str[i]==')' || str[i] == ']' || str[i]=='}'){
if(stack==NULL){
return 0;
}
if(!isMatching(pop(), str[i])){
return 0;
}
}
i++;
}
if(stack==NULL){
return 1; // balanced parenthesis
}else{
return 0; // not balanced parenthesis
}
}
这是用户输入字符串并测试它是否“平衡”的主要功能。
int main(){
char str[MAX];
int flag;
printf("Enter the string with the brackets and etc.\n");
fgets(str, sizeof(str),stdin);
flag=isBalanced(str);
if(flag==1){
printf("Balanced\n");
}
else{
printf("Not balanced\n");
}
return 0;
}
当我输入一个非常简单的例子时,我得到一个错误的答案,例如
Enter the string with the brackets and etc.
()
Not balanced
这应该输出“平衡”。我不明白这是怎么发生的。
【问题讨论】:
-
如果你在 top==0 时调用 pop 那么你将返回 stack[-1] - 这对我来说看起来不对。
-
...还有
if(stack==NULL)... -
@jmq 为什么会出错?
-
@user5329483 我应该使用不同的条件来检查堆栈是否为空吗?
-
stack[-1] 是错误的,因为使用负数组索引会导致未定义的行为。数组的有效索引是 0-49。