源程序如下
#include<iostream>
using namespace std;
struct Node
{
char n;
Node * next;
};
void push(Node *&pHead, char x)
{
Node *pNew = new Node;
pNew->n = x;
pNew->next = NULL;
if (!pHead)
{
pHead = pNew;
}
else
{
pNew->next = pHead;
pHead = pNew;
}
}
void printLink(const Node *pHead)
{
Node * pNow = (Node *)pHead;
while (pNow)
{
cout << pNow->n << " ";
pNow = pNow->next;
}
cout << endl;
}
char pop(Node *&pHead)
{
if (!pHead)
{
return 0;
}
int x = pHead->n;
Node * p = pHead;
pHead = pHead->next;
delete p;
return x;
}
int main()
{
Node *pHead = NULL;
char c[256];
char * p = c;
cin >> c;
while (1)
{
if (*p == '\0')
break;
if (!pHead)
{
push(pHead, *p);
}
else
{
if(pHead->n == '(' && *p == ')')
{
pop(pHead);
}
else
{
push(pHead, *p);
}
}
p++;
}
if (!pHead)
{
cout << "匹配" << endl;
}
else
cout << "不匹配" << endl;
return 0;
}
运行效果: