栈练习——括号匹配
【摘要】 括号匹配
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
#define OVERFLOW -2
#define OK 1
#define ERROR -1
typedef int Status;
typedef char...
括号匹配
#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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
请输入字符串:fdas(fd(
左括号多!
- 1
- 2
文章来源: ruochen.blog.csdn.net,作者:若尘,版权归原作者所有,如需转载,请联系作者。
原文链接:ruochen.blog.csdn.net/article/details/102903796
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)