给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct Node {
char val;
struct Node *next;
struct Node *pre;
} Node;
typedef struct stack {
Node *head;
Node *tail;
int size;
} stack;
bool isValid(char *s) {
if (s == NULL) {
return false;
}
int i = 0;
stack *st = (stack *) malloc(sizeof(stack));
if (st == NULL) {
return false;
}
st->size = 0;
st->head = NULL;
st->tail = NULL;
while (s[i] != '\0') {
if (s[i] == '{' || s[i] == '(' || s[i] == '[') {
Node *node = (Node *) malloc(sizeof(Node));
if (node == NULL) {
printf("a %d", st->size);
return false;
}
node->val = s[i];
node->next = NULL;
node->pre = NULL;
if (st->size == 0) {
st->head = node;
} else {
node->pre = st->tail;
st->tail->next = node;
}
st->tail = node;
st->size += 1;
} else if (s[i] == '}' || s[i] == ')' || s[i] == ']') {
if (st->size == 0) {
return false;
}
if ((s[i] == '}' && st->tail->val != '{') ||
(s[i] == ')' && st->tail->val != '(') ||
(s[i] == ']' && st->tail->val != '[')) {
printf("b %d", st->size);
return false;
} else {
Node *denode = st->tail;
st->tail = st->tail->pre;
if (st->tail != NULL) {
st->tail->next = NULL;
} else {
st->head = NULL;
}
free(denode);
st->size -= 1;
}
}
i++;
}
printf("e %d", st->size);
bool result = (st->size == 0) ? true : false;
free(st);
return result;
}
易错点:
- 释放节点内存后,需要将前一个节点的 next 指针正确地设置为 NULL,否则容易导致链表出现错误。此外,在释放节点后,应将 size 减一
- 在释放栈顶节点后,更新链表的尾部指针 st->tail。在释放节点后,如果链表不为空,需要将上一个节点的 next 指针设置为 NULL,以确保链表的完整性。如果链表为空,那么将链表的头部指针 st->head 设置为 NULL,表示链表已经空了。这样做是为了在后续操作中能够正确地处理链表的头部和尾部指针。
2550

被折叠的 条评论
为什么被折叠?



