用VC++编程,读取任何文本文件,查看圆括号和大括号是否匹配,只许成对出现,并按正常方式排列。

来源:百度知道 编辑:UC知道 时间:2024/06/07 19:30:10
例({((***)(***))})

如果不要求用栈来完成的话,做两个标志,一个表示"(",读到"("就+1,读到")"就-1。循环过程中只要<0就认为不匹配,{同理。
如果要求用堆栈来实现,可以参考下例,其中main用于测试,IsMatched(char* p)用来判断是否匹配:
#include<iostream>
using namespace std;

struct Node
{
char ch;
Node *next;
};

bool IsMatched(const char *pStr);

int main()
{
char *p = "({((***)(***))})";
if (IsMatched(p))
{
cout << "Matched!"<<endl;
}
else
cout << "Not Matched!"<<endl;
cin.get();
return 0;
}

bool IsMatched(const char *pStr)
{
Node *pParen = NULL;
Node *pBrack = NULL;
int i = 0;
Node *pTmp = NULL;
while (*(pStr+i) != '\0')
{
switch(*(pStr+i))
{
case'(':
// push
pTmp = new Node;
pTmp->next = pParen;
pTmp->ch = '(';
pParen