![]() |
#2
柒夏辰2016-10-13 22:10
#include<iostream>
using namespace std; const int max=100; template <class T> class stack { T data[max]; int top; public: stack(){top=-1;} void push(T x) { if(top==max-1) return; top++; data[top]=x; } void pop() { T x; if(top==-1) exit(0); x=data[top]; top--; } T gettop() { return data[top]; } bool empty() { return top=-1?1:0; } }; int main() { char c[200]; int d=0,i=0,j; stack<char> s; while(c[i]=getchar()&&c[i]!='\n') { if(c[i]=='(') { s.push(c[i]); } else if(c[i]=='[') { s.push(c[i]); } else if(c[i]=='{') { s.push(c[i]); } else if(c[i]==')') { if(s.gettop()=='(') { s.pop(); } } else if(c[i]==']') { if(s.gettop()=='{') { s.pop(); } } else if (c[i]=='}') { if(s.gettop()=='{') { s.pop(); } } i++; d++; } j=s.empty(); if(j==0) { cout<<"括号匹配成功"<<endl; } if(j==1) { cout<<"括号匹配不成功"<<endl; } return 0; } 有点小错 |
#include<iostream>
using namespace std;
const int max=100;
template <class T>
class stack
{
T data[max];
int top;
public:
stack(){top=-1;}
void push(T x)
{
if(top==max-1) return;
top++;
data[top]=x;
}
void pop()
{
T x;
if(top==-1) exit(0);
x=data[top];
top--;
}
T gettop()
{
return data[top];
}
bool empty()
{
return top=-1?1:0;
}
};
int main()
{
char c[200];
int d=0,i=0,j;
stack<char> s;
while(c[i]=getchar()&&c[i]!='\n')
{
if(c[i]=='(')
{
s.push(c[i]);
}
else if(c[i]=='[')
{
s.push(c[i]);
}
else if(c[i]=='{')
{
s.push(c[i]);
}
else if(c[i]==')')
{
if(s.gettop()=='(')
{
s.pop();
}
}
else if(c[i]==']')
{
if(s.gettop()==']')
{
s.pop();
}
}
else if (c[i]=='}')
{
if(s.gettop()=='}')
{
s.pop();
}
}
i++;
d++;
}
j=s.empty();
if(j==0)
{
cout<<"括号匹配成功"<<endl;
}
if(j==1)
{
cout<<"括号匹配不成功"<<endl;
}
return 0;
}