括号匹配
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
#define OVERFLOW -2
#define OK 1
#define ERROR -1
typedef int Status;
typedef char SElemType;
typedef struct StackNode {
SElemType data;
struct StackNode* next;
}StackNode, * LinkStack;
// 链栈初始化
void InitStack(LinkStack& S) {
S = NULL;
}
// 判断链栈是否为空
Status StackEmpty(LinkStack S) {
if (S == NULL) return 1;
else return 0;
}
Status GetTop(LinkStack S, SElemType& e) {
if (StackEmpty(S)) return ERROR;
e = S->data;
return OK;
}
// 入栈
Status Push(LinkStack& S, SElemType e) {
LinkStack p;
p = new StackNode;
if (!p) exit(OVERFLOW);
p->data = e;
p->next = S;
S = p;
return OK;
}
// 出栈
Status Pop(LinkStack& S) {
if (StackEmpty(S)) return ERROR;
LinkStack p;
p = S;
S = S->next;
delete p;
p = NULL;
return OK;
}
/*-----------括号匹配----------*/
int Match(string str) {
LinkStack S;
int i;
SElemType e;
InitStack(S);
for (i = 0; i < str.length(); i++) {
/*
此处不可使用strlen(str)
strlen() 参数为const char* 类型
---------------------------
char cstr[20];
strcpy(cstr, str.c_str());
---------------------------
*/
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
Push(S, str[i]);
if (str[i] == ')' || str[i] == ']' || str[i] == '}') {
if (StackEmpty(S)) {
cout << "右括号多!";
return ERROR;
}
else {
GetTop(S, e);
if((e == '(' && str[i] == ')') || (e == '['
&& str[i] == ']') || (e == '{' && str[i] == '}'))
Pop(S);
else {
cout << "次序乱!";
return ERROR;
}
}
}
}
if (StackEmpty(S)) {
cout << "匹配成功!";
return OK;
}
else {
cout << "左括号多!";
return ERROR;
}
}
int main()
{
string str;
cout << "请输入字符串:";
cin >> str;
Match(str);
return 0;
}
请输入字符串:fdas(fd(
左括号多!