【发布时间】:2017-08-11 23:22:02
【问题描述】:
这是一个使用堆栈检查 C 中括号平衡的程序,但它没有按预期工作。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char data;
struct node *next;
};
struct node *top = NULL; //top stores address of top element of stack
void push(char data) { //inserting element
struct node *temp = (node *)malloc(sizeof(struct node));
temp->data = data;
temp->next = NULL;
if (top == NULL) {
top = temp;
return;
}
temp->next = top;
top = temp;
}
void pop() { //removing element
struct node *temp = top;
if (top == NULL) {
printf("No element to delete");
return;
}
top = top->next;
free(temp);
}
char Top() { //fn tht return top element of stack
return top->data;
}
int isEmpty() {
if (top != NULL) {
return 1;
} else
return 0;
}
int ArePair(char opening, char closing) {
if (opening == '(' && closing == ')')
return 1;
else if (opening == '{' && closing == '}')
return 1;
else if (opening == '[' && closing == ']')
return 1;
return 0;
}
int Arebalanced(char exp[]) {
int i;
for (i = 0; i < strlen(exp); i++) {
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
push(exp[i]);
else if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']') {
if (isEmpty() || !ArePair(Top(), exp[i]))
return 0;
else
pop();
}
}
return isEmpty() ? 1 : 0;
}
int main() {
int i;
char a[50];
printf("Enter expession: ");
gets(a);
if (Arebalanced(a)) {
printf("balanced \n");
} else
printf("not balanced\n");
}
【问题讨论】:
-
isEmpty:if( top!=NULL)-->if( top==NULL) -
您遇到问题的输入是什么?什么不工作?
-
输入如:(a+b), )( , [(a+y)], 或任何其他表达式..
-
感谢 BLUEPIXY 。自上次 4rs 以来我一直在这样做,只是小错误..呵呵
-
另外,您使用 C++ 作为 C。
(node *):node在 C 中未声明。
标签: c data-structures stack