我将堆栈实现为链表,我想制作一个函数来告诉括号是否顺序良好,例如: (()) 是好的 ())( 是坏的。函数的逻辑现在不好,但我不知道为什么 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
中的这一行没有意义:
top->x = temp->sljedeci->x;
在上一行中,您将 temp->sljedeci
分配给 top
。所以这里引用的 x 成员实际上两边都是同一个,所以假设 top 和 temp->sljedeci 都不为 null没有什么。如果其中一个为 NULL,则调用 undefined behavior因为您取消引用空指针。所以去掉这条线。
您在 pop
中也存在内存泄漏:
temp = (stog*)malloc(sizeof(stog));
temp = top;
您分配内存并将其地址分配给 temp
,但随后立即用 top
的值覆盖该地址。
此处无需分配更多内存,因此请删除 malloc
调用。
关于c - Pop 在特定函数中仅起作用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59886477/