#include <stdio.h> #include <stdlib.h>

typedef int DataType; struct Node { DataType data; struct Node* next; }; typedef struct Node *PNode; typedef struct Node *LinkStack;

LinkStack SetNullStack_Link()
{ LinkStack top = (LinkStack)malloc(sizeof(struct Node)); if (top != NULL) top->next = NULL; else printf("Alloc failure"); return top;
}

int IsNullStack_link(LinkStack top) { if (top->next == NULL) return 1; else return 0; }

void Push_link(LinkStack top, DataType x) { PNode p; p = (PNode)malloc(sizeof(struct Node)); if (p == NULL) printf("Alloc failure"); else { p->data = x; p->next = top->next; top->next = p; } } void Pop_link(LinkStack top) { PNode p; if (top->next == NULL) printf("it is empty stack!"); else { p = top->next; top->next = p->next; free(p); } } DataType Top_link(LinkStack top) { if (top->next == NULL) { printf("It is empty stack!"); return 0; } else return top->next->data; }

void BracketMatch(LinkStack top) { int flag = 1; char ch, temp; scanf("%c", &ch); while (ch != '#') { switch (ch) { case '[': case '(': Push_link(top, ch); break; case ')': if (Top_link(top) == '(') Pop_link(top); else flag = 0; break; case ']': if (Top_link(top) == '[') Pop_link(top); else flag = 0; break; }//swith scanf("%c", &ch); }//while

if (IsNullStack_link(top) == 1)
    printf("yes!");
else
    printf("no!");

}

int main() { LinkStack mystack = NULL; mystack = SetNullStack_Link(); BracketMatch(mystack); return 0; }

// 代码说明: // 1. 使用链表实现栈结构,方便动态分配内存。 // 2. 使用 BracketMatch 函数进行括号匹配判断。 // 3. 当遇到左括号时,将其入栈。 // 4. 当遇到右括号时,判断栈顶元素是否为对应的左括号,若是则出栈,否则匹配失败。 // 5. 最后,判断栈是否为空,为空则匹配成功,否则匹配失败。


原文地址: https://www.cveoy.top/t/topic/pmmx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录