#include<stdio.h>
#include<stdlib.h>
#include<string>
#define OK 1;
#define ERROR 0;
using namespace std;
typedef struct StackNode
{
char data;
struct StackNode* pNext;
}stackNode, *pStackNode;
int flag = 0;
int init(pStackNode& pHead)
{
flag = 0;
pHead = NULL;
return OK;
}
int push(pStackNode& pHead, char c)
{
flag--;
stackNode* p;
p = (stackNode*)malloc(sizeof(stackNode));
p->data = c;
p->pNext = pHead;
pHead = p;
return OK;
}
char pop(pStackNode& pHead)
{
if (pHead == NULL)
{
return ERROR;
}
flag++;
pStackNode p;
p = pHead;
pHead = pHead->pNext;
return p->data;
}
bool isEmpty(pStackNode pHead)
{
if (pHead == NULL)
{
return true;
}
else
{
return false;
}
}
bool isPair(char a, char b)
{
if (a == '('&&b == ')')
{
return true;
}
else if (a == '['&&b == ']')
{
return true;
}
else if (a== '{'&&b == '}')
{
return true;
}
else
{
return false;
}
}
bool judge(string s)
{
pStackNode pHead;
init(pHead);
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
{
push(pHead, s[i]);
}
if (s[i] == ')' || s[i] == ']' || s[i] == '}')
{
if (!isPair(pop(pHead), s[i]))
{
return false;
}
}
}
if (isEmpty(pHead)&& flag==0)
{
return true;
}
else
{
return false;
}
}
int main()
{
//string s="3*{2*[2*(x+y)/(1-x)]+3*(3+4)})";
string s = "2*(2+1)";
if (judge(s))
{
printf("匹配!");
}
else
{
printf("不匹配!");
}
return 0;
}
数据结构第三章基本作业(表达式匹配)
最新推荐文章于 2022-05-09 20:02:07 发布