【发布时间】:2020-05-10 04:37:21
【问题描述】:
我将堆栈实现为链表,我想创建一个函数来判断括号是否井井有条,例如:(()) 是好的 ())( 是坏的。函数的逻辑现在不好,但我不知道为什么 pop() 只工作一次。这是我的代码(stog 是堆栈,sljedeci 是下一个):
struct stog {
int x;
stog *sljedeci;
};
typedef struct stog stog;
stog *top;
char pop() {
stog *temp;
temp = (stog*)malloc(sizeof(stog));
temp = top;
char n = temp->x;
top = temp->sljedeci;
top->x = temp->sljedeci->x;
free(temp);
return n;
}
void init() {
top = NULL;
}
void push(char x) {
stog *temp;
temp=(stog*)malloc(sizeof(stog));
temp->x = x;
temp->sljedeci = top;
top = temp;
}
void Brackets(const char* msg) {
char z;
for (int i = 0; i < strlen(msg); i++) {
if (msg[i] == '(') {
push('(');
}
if (msg[i]==')'){
z = pop();
printf("Bad\n");
}
}
}
int main() {
const char* msg = "(())";
init();
Brackets(msg);
return 0;
}
输出是:
不好
应该是:
不好 不好
编辑:添加了 init() 和 push() 函数
【问题讨论】:
-
您在
pop中的malloc之后立即泄漏内存。 -
@Aplexas 函数pop整体没有意义。
-
你的意思是我不需要 top->x = temp->sljedeci->x; ?
-
@Aplexas 不,这根本没有任何意义
-
阅读How to Ask。
init()、push()和pop()都是相互依赖的正确行为,您应该将它们全部发布。你所拥有的不是minimal reproducible example
标签: c memory-management stack singly-linked-list c-strings