先定义堆栈的几个基本操作,再设计一主函数利用堆栈的操作完成以下功能:假设一个算术表达式中可以包含三种括号:()[]{},且这三种括号可以按任意次序嵌套使用(如:…[…{…}…[…]…]…(…))。编写判别给定表达式中所含括号是否正确配对出现的算法,已知表达式已存入数据元素为字符的单链表中。
#include<iostream>
using namespace std;
typedef char ElemType;
#define OK 1
#define ERROR 0
typedef struct LNode //链表
{
ElemType data; //数据域
struct LNode *next; //指针域
int length; //长度
}LNode, *LinkList;
typedef struct StackNode //链栈
{
ElemType data; //数据域
struct StackNode *next; //指针域
}StackNode, *LinkStack;
LinkList InitList(LinkList &L) //初始化链表
{
L = new LNode;
L->next = NULL;
L->length = 0;
return L;
}
int CreateList(LinkList &L, int n) //后插法创建链式线性表
{
LinkList r = L;
ElemType e = '0';
cout << "请输入链表中的元素个数:";
cin >> n;
cout << "请依次输入元素:";
for (int i = 0; i < n; i++)
{
LinkList p;
cin >> e;
p = new LNode;
p->data = e;
p->next = NULL;
r->next = p;
r = p;
L->length++;
}
return OK;
}
LinkStack InitStack(LinkStack &S)//初始化栈
{
S = NULL;
return S;
}
int PushStack(LinkStack &S, ElemType e)//入栈
{
LinkStack p;
p = new StackNode;
p->data = e;
p->next = S;
S = p;
return OK;
}
int PopStack(LinkStack &S)//出栈
{
ElemType e;
if (S == NULL) return ERROR;
e = S->data;
LinkStack q = S;
S = S->next;
delete q;
return OK;
}
int GetLength(LinkStack S) //获取栈的长度
{
LinkStack p = S;
int j = 0;
while (p)
{
p = p->next;
j++;
}
if (p) j++;
return j;
}
ElemType GetTop(LinkStack S)//取栈顶元素
{
if (S != NULL) return S->data;
if (S == NULL) cout << "栈顶没有元素!"; return '0';
}
int IsMatch(LinkList L, LinkStack &S) //是否匹配成功
{
LinkList p = L->next, q = L->next;
bool TheLast = true;
while (p->data != '}' && p->data != ']' && p->data != ')')
{
PushStack(S, p->data);
if (p->next == NULL && p->data != '}'&&p->data != ']'&&p->data != ')')
{
cout << "匹配失败!" << endl; TheLast = 0; break;
}
p = p->next;
}
cout << endl;
bool IsSuccess = true;
while (p)
{
if (p->data == '}'&& GetTop(S) == '{')
{
PopStack(S);
}
else if (p->data == ']'&& GetTop(S) == '[')
{
PopStack(S);
}
else if (p->data == ')'&& GetTop(S) == '(')
{
PopStack(S);
}
else if (p->data == '{' || p->data == '[' || p->data == '(')
{
PushStack(S, p->data);
}
else
{
IsSuccess = false;
}
p = p->next;
}
if (IsSuccess && !GetLength(S)) cout << "匹配成功!" << endl;
else if(TheLast) cout << "匹配失败!" << endl;
return OK;
}
int main()
{
LinkList L;
LinkStack S;
InitStack(S);
InitList(L);
int n = 0;
CreateList(L, n);
IsMatch(L, S);
system("pause");
}