利用栈实现字符匹配~~
#include<iostream>
#include<stdlib.h>using namespace std;
typedef char ElemType;
const int MaxSize=100;
struct Stack
{
ElemType stack[MaxSize];
int top;
};
void InitStack(Stack& S)
{
S.top = -1;
}
void Push(Stack& S, ElemType item)
{
S.top++;
S.stack[S.top] = item;
}
ElemType Pop(Stack& S)
{
if(S.top==-1)
{
cout << " Stack is empty! " << endl;
exit(1);
}
S.top--;
return S.stack[S.top+1];
}
ElemType Peek(Stack& S)
{
if(S.top==-1)
{
cout << " Stack is empty! " << endl;
exit(1);
}
return S.stack[S.top];
}
bool EmptyStack(Stack& S)
{
return S.top == -1;
}
void ClearStack(Stack& S)
{
S.top = -1;
}
int main()
{
Stack a;
InitStack(a);
while(1)
{
char ch[100]={0};
cout << "请输入任意的表达式:";
cin.getline(ch,100);
for(int i=0; ch[i]!='\0'; i++)
{
switch(ch[i])
{
case '(': Push(a,ch[i]);break;
case ')': if(Peek(a)=='(') Pop(a);
else return 0;
}
}
if(EmptyStack(a))
{
cout << " 配对成功! " << endl;
}
else
{
cout << " 配对不成功! " << endl;
}
}
return 0;
}