设计思路:
3.0.1.cpp
#include<iostream>
using namespace std;
const int StackSize=100;
template<typename Type> class SeqStack{
private:
Type data[StackSize];
int top;
public:
SeqStack(int sz){top=-1;}
SeqStack(){top=-1;}
~SeqStack(){}
void Push(Type x);
Type Pop();
Type Pop2();
Type getTop();
int Empty();
void Print();
};
template<typename Type> void SeqStack<Type>::Push(Type x){
if(top==StackSize-1) cout<<"Stack is full"<<endl;
data[++top]=x;
}
template<typename Type> Type SeqStack<Type>::Pop(){
if(top==-1) cout<<"Stack is empty"<<endl;
else
{
for(int i=top;i>=0;i--)
{
Type x=data[i];
cout<<x<<" ";
}
cout<<endl;
}
}
template<typename Type>Type SeqStack<Type>::Pop2(){
return data[top--]; //注意 top--
// top--;
}
template<typename Type> Type SeqStack<Type>::getTop(){
if(top==-1) cout<<"stack is Empty";
return data[top];
/* if(Empty())
cout<< " iii";
*/
}
template<typename Type> int SeqStack<Type>::Empty(){
int m = top==-1?1:0;
return m;
}
template<typename Type> void SeqStack<Type>::Print(){
for(int i=0;i<=top;i++)
cout<<data[i]<<" ";
cout<<endl;
}
3.0.2.cpp
#include<iostream>
#include "3.0.1.cpp"
const int DefaultSize=100;
using namespace std;
class pp{
private:
char ch;
char *c;
const int maxsize;
int currentsize;
public:
pp(int sz):maxsize(sz)//使用初始化列表进行初始化
{
if(sz>0)
c=new char[maxsize];
}
~pp(){}
bool op(char ch){ //判断当前字符是否为括号
if(ch=='('||ch=='['||ch=='{'||ch=='}'||ch==']'||ch==')')
return true;
else
return false;
}
bool pipei(char *c) // bool 类型 的使用 ,0.3.1 中判断为空的函数
{
SeqStack<char> stack(100);
for(int i=0;i<=maxsize;i++)
{
if(op(c[i])==0)
{
c[i]++;
}
else
if(c[i]=='('||c[i]=='['||c[i]=='{')
{
stack.Push(c[i]);
c[i]++;
}
else //右括号
{
if(stack.Empty())
{
cout<<"右括号多于左括号"<<endl;
return false;
}
// 如果非空,判断是否匹配
if(c[i]==')'&&stack.getTop()=='(' ||c[i]==']'&&stack.getTop()=='['|| c[i] =='}'&&stack.getTop()=='{')
{
stack.Pop2();
c[i]++;
}
else
{
cout<<"左右括号不匹配"<<endl;
return false;
}
}
}
if(!stack.Empty())
{
cout << "左括号多于右括号" << endl;
return false;
}
else
{
cout << "左右括号匹配正确" << endl;
stack.Print();
return true;
}
}
};
3.0.test.cpp
#include<iostream>
#include "3.0.2.cpp"
using namespace std;
int main()
{
char a[] = "(())abc{[(])}"; // 左右括号不匹配
char b[] = "(()))abc{[]}"; // 右括号多于左括号
char c[] = "(())abc{[]()}"; // 左右括号匹配正确
char e[]=")";
pp p(13);
cout << p.pipei(a) << endl;
cout << p.pipei(b) << endl;
cout << p.pipei(e) << endl;
}
代码还有点小错误,在加入某些试验数据后,不能正确判断括号是否匹配。但是单独测试该数据时,可以正确判断。原因尚未知。
参考:https://blog.csdn.net/qq_34992845/article/details/70313454