赞
踩
本文代码中的栈用不带头结点的链栈实现
假设一个算术表达式中包含圆括号、方括号和花括号3种类型的括号,编写一个算法来判別表式中的括号是否配対,以字符“ \0”作为算术表式的结束符。
ps:题目来源2025王道数据结构
严格按照上述的思路编写的代码
#include <iostream> #include <cstring> #include <cstdlib> #define MAXSIZE 100 using namespace std; typedef struct Linknode { char data; Linknode *next; }Linknode; bool isEmpty(Linknode *top) { return top == NULL; } void push(Linknode **top, char val) { Linknode *newnode = (Linknode*)malloc(sizeof(Linknode)); if (newnode == NULL) { printf("内存分配失败,入栈操作失败。\n"); return; } newnode->data = val; newnode->next = *top; *top = newnode; } void pop(Linknode **top, char &val) { if (isEmpty(*top)) { printf("栈已空,无法进行出栈操作。\n"); return; } Linknode *tmp = *top; val = (*top)->data; *top = (*top)->next; free(tmp); } int main() { char arr[MAXSIZE]; cin >> arr; int i = 0; Linknode *top = NULL; while (arr[i] != '\0') { if (arr[i] == '(' || arr[i] == '[' || arr[i] == '{') push(&top, arr[i]); else { char ch; if (isEmpty(top)) { cout << "括号非法!!!" << endl; return 0; } pop(&top, ch); if ((ch == '(' && arr[i] != ')') || (ch == '[' && arr[i] != ']') || (ch == '{' && arr[i] != '}')) { cout << "括号非法!!!" << endl; return 0; } } i++; } if (!isEmpty(top)) cout << "括号非法!!!" << endl; else cout << "括号合法" << endl; return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。