顺序栈的c++实现及利用其实现括号的匹配

#include<iostream>
#include<cassert>
#include<cstring>
#include<string>
using namespace std;
int maxLength=100;
const int stackIncreament = 20;
template<class T>
class Stack{
public:
Stack(){}
virtual void Push(const T& x)=0;
virtual bool Pop(T& x)=0;
virtual bool getPop(T& x)=0;
virtual bool IsEmpty()=0;
virtual bool IsFull()=0;
virtual int getSize()=0;
};
template<class T>
class SeqStack:public Stack<T>{
public:
SeqStack(int sz=50);
~SeqStack(){delete []elements;}
void Push(const T& x);
bool Pop(T& x);
bool getPop(T& x);
bool IsEmpty(){return (top==-1)? true:false;}
bool IsFull() {return (top==maxSize-1)?true:false;}
int getSize(){return top+1;}
void MakeEmpty(){top=-1;}

private:
T *elements;
int top;
int maxSize;
void overflowProcess();

};
template<class T>
SeqStack<T>::SeqStack(int sz){
top=-1;
maxSize=sz;
elements = new T[maxSize];
assert(elements!=NULL);
}

template<class T>
void SeqStack<T>::Push(const T& x)
{
if(IsFull()==true)
overflowProcess();
elements[++top]=x;
}

template<class T>
bool SeqStack<T>::Pop(T& x)
{
if(IsEmpty()==true)
return false;// cout<<top<<endl;
x=elements[top--];

return true;
}

template<class T>
bool SeqStack<T>::getPop(T& x)
{
if(IsEmpty()==true)
return false;
x=elements[top];
return true;

}

template<class T>
void SeqStack<T>::overflowProcess(){
T *newArray = new T[maxSize+stackIncreament];
if(newArray==NULL)
{
cout<<"内存分配失败"<<endl;
return ;
}
for(int i=0;i<=top;i++)
{
newArray[i]=elements[i];
}
maxSize=maxSize+stackIncreament;
delete []elements;
elements =newArray;
}

void printMatchedPairs(string expression)
{
SeqStack<int> s(maxLength);
SeqStack<int> a(maxLength);
SeqStack<int> b(maxLength);
int j,c,d,r,t=0,length=expression.length();
int e=0,m=0;
for(int i=1;i<=length+1;i++)
{
if(expression[i-1]=='(')
s.Push(i);
else if(expression[i-1]==')')
{
for(int r=1;r<=i;r++)
if(expression[r-1]==']'||expression[r-1]=='}')
t++;
if(t!=0)
{
cout<<"failure";
m++;
break;
}
s.Pop(j);
}
else if(expression[i-1]=='[')
a.Push(i);
else if(expression[i-1]==']')
{
for(int r=1;r<=i;r++)
if(expression[r-1]=='}')
e++;
if(e!=0)
{
cout<<"failure";
m++;
break;
}
a.Pop(j);
}
else if(expression[i-1]=='{')
b.Push(i);
else if(expression[i-1]=='}')
b.Pop(d);
}
if(m==0)
{
if(s.IsEmpty()==true&&a.IsEmpty()==true&&b.IsEmpty()==true)
{
cout<<"success";

}
else
cout<<"failure";
}

}
int main()
{
string expression;
cin>>expression;
printMatchedPairs(expression);

return 0;
}

上一篇:js函数定义的三种方式


下一篇:Explain in detail the steps/processes that occur from the moment you type a URL in a browser and hit enter