#include<iostream>
using namespace std;
typedef char SElemType;
typedef int Status;
typedef struct SNode {
int data;
struct SNode* next;
} SNode, * LinkStack;
Status InitStack(LinkStack& S) {
S = NULL;
return 1;
}
bool StackEmpty(LinkStack S) {
if (!S)
return true;
return false;
}
Status Push(LinkStack& S, SElemType e) {
SNode* p = new SNode;
if (!p) {
return -1;
}
p->data = e;
p->next = S;
S = p;
return 1;
}
Status Pop(LinkStack& S, SElemType& e) {
SNode* p;
if (!S)
return 0;
e = S->data;
p = S;
S = S->next;
delete p;
return 1;
}
Status GetTop(LinkStack& S) {
if (!S)
return 0;
return S->data;
}
Status Matching() {
char ch;
SElemType x;
LinkStack S;
InitStack(S);
int flag = 1;
cin >> ch;
while (ch != '#' && flag)
{
switch (ch) {
case '[':
case '(':
Push(S, ch);
break;
case ')':
if (!StackEmpty(S) && GetTop(S) == '(')
Pop(S, x);
else
flag = 0;
break;
case ']':
if (!StackEmpty(S) && GetTop(S) == '[')
Pop(S, x);
else
flag = 0;
break;
}
cin >> ch;
}
if (StackEmpty(S) && flag)
return true;
else
return false;
}
int main() {
LinkStack S;
cout << "请输入表达式#结束:" << endl;
int flag = (int)Matching();
if (flag)
cout << "匹配成功!" << endl;
else
cout << "匹配失败!" << endl;
return 0;
}
用栈实现括号匹配
最新推荐文章于 2023-06-24 21:54:49 发布