个人觉得书上写的函数太乱,自己整理后写了一个,略简单
Stack.h
#include<iostream>
#include<assert.h>
using namespace std;
template <class T>
struct LinkNode {
T data ;
LinkNode <T> *link ;
};
//上面是LinkNode的声明
template <class T>
class Stack {
public:
//需要写的内容有Pop,Push,IsEmpty;
Stack ():top(NULL) {}
void Push ( const T & x ){//进栈
top =new LinkNode <T> (x ,top);
assert ( top !=NULL ) ;
}
bool Pop (){//退栈
if( IsEmpty() == true ) return false ;
LinkNode <T> *p =top ;
top = top->link ;
delete p;
return true ;
}
bool IsEmpty () const { return ( top == NULL )?true :false ; }
private:
LinkNode <T> *top ;
};
PMP.h(判断用的)
#include<iostream>
#include<string.h>
#include"Stack.h"
using namespace std;
//int maxLength = 100 ; 没有开辟一个新的栈却依旧可以执行代码 ,通过push将一个一个字符扔进栈,通过pop出栈,没有考虑栈的容量,代码无定义
void PrintMatchedPairs (string expression){
//需要开辟一个栈用来存放括号
Stack <char> s;
int length = expression.size();
for(int i = 1; i <= length ; i++){
if( expression [i-1] == '(' )//如果检测的是左括号;执行进栈的操作
s.Push(i) ;
else if( expression [i-1] == ')' ){//如果检测的是右括号,判断栈是否空,若栈不空,退栈成功
if(s.Pop() == true )
cout<<"匹配成功"<<endl;
else
cout<<"匹配失败,没有左括号参与匹配"<<endl;
}
}
while (s.IsEmpty () == false ){
s.Pop();
cout<<"栈中还有多余的括号,匹配失败 "<<endl;
}
}
//所需要执行的堆栈函数有Pop, Push, IsEmpty
main
#include<iostream>
#include<string>
#include"PMP.h"
using namespace std;
void main(){
cout<<"请输入想判断的字符串 : ";
string s;
cin >> s;
PrintMatchedPairs (s);
system ("pause");
}