没用模版写的,也没考虑多于的情况,练手。
//括号配对问题
#include<iostream>
using namespace std;
class stack
{
private:
int *a;
int top;
public:
stack(int sz=100);
void Push(const int &x);
bool Pop(int &);
};
void stack::Push(const int &x)
{
a[++top]=x;
}
bool stack::Pop(int &x)
{
x=a[top--];
return true;
}
stack::stack(int sz)
{
top=-1;
a=new int[sz];
}
int main()
{
cout<<"please enter a line"<<endl;
char str[20];
cin>>str;
stack ch;
void C(char *,stack);
C(str,ch);
system("pause");
return 0;
}
void C(char str[],stack s)
{
int i=0;int ch;
for(i=0;i<strlen(str);i++)
{
if(str[i]=='(')
s.Push(i+1);
else if(str[i]==')')
{ if(s.Pop(ch))
cout<<"第"<<ch<<"个左括号与第"<<i+1<<"右括号匹配"<<endl;
}
}
}