C语言实现LeetCode1021时push函数报错,请求排查问题
问题排查与修正方案
一、Push函数错误的核心原因
你的push语句x->item[++x->top] = y;出错,大概率是栈的初始化逻辑错误:
- 标准栈的
top指针初始值应为-1(表示空栈),如果你的代码里把top初始化为0,执行++x->top会直接访问索引1,若栈的初始容量不足,就会触发数组越界错误。 - 另外,如果栈的
item数组未正确分配内存,或者分配的大小不足以处理输入字符串的长度,也会导致写入错误。
二、完整代码的常见问题排查(结合LeetCode1021题逻辑)
假设你的栈结构定义和初始化代码存在类似下面的错误:
typedef struct Stack { int top; int* item; } Stack; Stack* createStack(int size) { Stack* s = malloc(sizeof(Stack)); s->top = 0; // 错误:初始top应为-1 s->item = malloc(size * sizeof(int)); return s; }
这里的top初始值错误是核心问题,修正后top应设为-1。
另外,针对LeetCode1021题的逻辑,用整数栈跟踪有效括号时,没必要存储括号本身,只需通过栈的深度判断原语边界:
- 遇到
'('时push一个标记(比如1),遇到')'时pop - 当栈从空变为非空时,跳过当前的
'('(外层左括号) - 当栈从非空变为空时,跳过当前的
')'(外层右括号) - 其他情况的括号都加入结果字符串
三、修正后的完整代码示例
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Stack { int top; int* item; } Stack; Stack* createStack(int size) { Stack* s = (Stack*)malloc(sizeof(Stack)); if (!s) return NULL; s->top = -1; // 正确初始化:空栈top为-1 s->item = (int*)malloc(size * sizeof(int)); if (!s->item) { free(s); return NULL; } return s; } int isEmpty(Stack* s) { return s->top == -1; } void push(Stack* s, int val) { // 可添加容量检查,避免越界 s->item[++s->top] = val; } void pop(Stack* s) { if (!isEmpty(s)) { s->top--; } } char* removeOuterParentheses(char* s) { int len = strlen(s); char* res = (char*)malloc((len + 1) * sizeof(char)); if (!res) return NULL; Stack* stack = createStack(len); if (!stack) { free(res); return NULL; } int idx = 0; for (int i = 0; i < len; i++) { if (s[i] == '(') { if (!isEmpty(stack)) { // 不是外层左括号,加入结果 res[idx++] = s[i]; } push(stack, 1); } else { pop(stack); if (!isEmpty(stack)) { // 不是外层右括号,加入结果 res[idx++] = s[i]; } } } res[idx] = '\0'; // 释放内存,避免泄漏 free(stack->item); free(stack); return res; } // 测试用例 int main() { char test[] = "(()())(())"; char* result = removeOuterParentheses(test); printf("%s\n", result); // 应输出 "()()()" free(result); return 0; }
四、额外优化建议
其实LeetCode1021题完全可以不用栈,用一个整数计数器替代,更高效且避免栈的内存管理问题:
char* removeOuterParentheses(char* s) { int len = strlen(s); char* res = malloc(len + 1); int idx = 0, count = 0; for (int i = 0; i < len; i++) { if (s[i] == '(') { if (count > 0) res[idx++] = s[i]; count++; } else { count--; if (count > 0) res[idx++] = s[i]; } } res[idx] = '\0'; return res; }
内容的提问来源于stack exchange,提问作者Archit Chhajed
相关产品推荐
相关产品推荐

