输入一串括号包含以下括号种类:(、)、[、]、{、}。试利用顺序栈或链栈检查输入括号序列的匹配情况;
时间: 2023-10-30 22:12:20 浏览: 86
算法步骤:
1.初始化一个空栈;
2.从左到右遍历输入括号序列中的每个括号;
3.如果遇到左括号 (、[、{,则将其压入栈中;
4.如果遇到右括号 )、]、},则取出栈顶元素进行匹配;
a.如果栈为空,则说明右括号比左括号多,返回错误;
b.如果栈顶元素不是对应的左括号,返回错误;
c.如果栈顶元素是对应的左括号,则将其弹出栈;
5.遍历完全部括号后,如果栈不为空,则说明左括号比右括号多,返回错误;
6.否则,返回正确。
代码如下(使用顺序栈):
```c++
#include <iostream>
using namespace std;
const int MAXSIZE = 100; // 栈的最大容量
typedef struct {
char data[MAXSIZE];
int top;
} SqStack;
void InitStack(SqStack &S) {
S.top = -1;
}
bool StackEmpty(SqStack S) {
if (S.top == -1)
return true;
else
return false;
}
bool Push(SqStack &S, char e) {
if (S.top == MAXSIZE - 1) // 栈满
return false;
S.top++;
S.data[S.top] = e;
return true;
}
bool Pop(SqStack &S, char &e) {
if (S.top == -1) // 栈空
return false;
e = S.data[S.top];
S.top--;
return true;
}
bool Match(char left, char right) { // 判断左右括号是否匹配
if (left == '(' && right == ')')
return true;
else if (left == '[' && right == ']')
return true;
else if (left == '{' && right == '}')
return true;
else
return false;
}
bool CheckBracket(char s[]) {
SqStack S;
InitStack(S);
int i = 0;
while (s[i] != '\0') {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') { // 左括号入栈
Push(S, s[i]);
} else if (s[i] == ')' || s[i] == ']' || s[i] == '}') { // 右括号出栈并判断是否匹配
char e;
if (Pop(S, e) == false || Match(e, s[i]) == false)
return false;
}
i++;
}
if (StackEmpty(S) == true)
return true;
else
return false;
}
int main() {
char s[] = "[(1+2)*(3-4)]";
if (CheckBracket(s) == true)
cout << "括号匹配" << endl;
else
cout << "括号不匹配" << endl;
return 0;
}
```
代码如下(使用链栈):
```c++
#include <iostream>
using namespace std;
typedef struct LinkNode {
char data;
struct LinkNode *next;
} *LiStack;
void InitStack(LiStack &S) {
S = NULL;
}
bool StackEmpty(LiStack S) {
if (S == NULL)
return true;
else
return false;
}
bool Push(LiStack &S, char e) {
LinkNode *p = new LinkNode;
p->data = e;
p->next = S;
S = p;
return true;
}
bool Pop(LiStack &S, char &e) {
if (S == NULL) // 栈空
return false;
e = S->data;
LinkNode *p = S;
S = S->next;
delete p;
return true;
}
bool Match(char left, char right) { // 判断左右括号是否匹配
if (left == '(' && right == ')')
return true;
else if (left == '[' && right == ']')
return true;
else if (left == '{' && right == '}')
return true;
else
return false;
}
bool CheckBracket(char s[]) {
LiStack S;
InitStack(S);
int i = 0;
while (s[i] != '\0') {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') { // 左括号入栈
Push(S, s[i]);
} else if (s[i] == ')' || s[i] == ']' || s[i] == '}') { // 右括号出栈并判断是否匹配
char e;
if (Pop(S, e) == false || Match(e, s[i]) == false)
return false;
}
i++;
}
if (StackEmpty(S) == true)
return true;
else
return false;
}
int main() {
char s[] = "[(1+2)*(3-4)]";
if (CheckBracket(s) == true)
cout << "括号匹配" << endl;
else
cout << "括号不匹配" << endl;
return 0;
}
```
阅读全文