参考《数据结构》
注:
1. 纯虚函数必须要定义,否则会出现error LNK2001: unresolvedexternal symbol "public: virtual bool __thiscallSeqStack<int>::getTop(int &)const
.h
const int size = 50;
template <class T>
class Stack {
public:
Stack(){}
//元素x入栈
virtual void Push(const T& x) = 0;
//栈顶元素出栈,由x返回
virtual bool Pop(T& x) = 0;
//读取栈顶元素,由x返回
virtual bool getTop(T& x) const = 0;
//判断栈空
virtual bool isEmpty() const = 0;
//判断栈满
virtual bool isFull() const = 0;
//计算栈中元素个数
virtual int getSize() const = 0;
};
.cpp
#include "stack.h"
#include <assert.h>
#include <stdlib.h>
#include <iostream.h>
const int stackIncreatement = 20;
template <class T>
class SeqStack:public Stack<T> {
public:
SeqStack(int sz = 50);
~SeqStack() {delete []elements;}
void Push(const T& x);
//if(isboolFull()),则溢出处理,否则Push(x)
bool Pop(T& x);
//if(isEmpty()),则返回false, 否则Pop(x)
bool getTop(T& x) const;
//if(isEmpty()),则返回false
bool isEmpty() const {return top == -1;};
//return getSize();
bool isFull() const {return top == maxSize-1;};
//return maxSize - getsize();
int getSize() const{return top+1;}
void makeEmpty() {top = -1;}
friend ostream& operator <<(ostream& out, SeqStack<T>& s);
private:
T* elements;
//top 表示最后存储的元素的位置
int top;
int maxSize;
void overflowProcess();
};
template <class T>
SeqStack<T>::SeqStack(int sz):maxSize(sz), top(-1) {
elements = new T[maxSize];
assert(elements != NULL);
};
template <class T>
void SeqStack<T>::overflowProcess() {
//私有函数,扩充栈的存储空间
T* newArray = new T[maxSize + stackIncreatement];
if(newArray == NULL) {
cerr<<"Memory failed"<<endl;
exit(1);
}
for(int i = 0; i <= top; i++) {
newArray[i] = elements[i];
}
maxSize += stackIncreatement;
delete []elements;
elements = newArray;
};
template <class T>
void SeqStack<T>::Push(const T& x) {
if(isFull()) {
overflowProcess();
}
elements[++top] = x;
};
template <class T>
bool SeqStack<T>::Pop(T& x) {
if(isEmpty()) {
return false;
}
x = elements[top--];
return true;
};
template <class T>
bool SeqStack<T>::getTop(T& x) {
if(isEmpty()) {
return false;
}
x = element[top];
return true;
};
main。cpp
#include <string.h>
#include <stdio.h>
#include "SeqStack.h"
const int maxLength = 100;
bool PrintMatchedPairs(char* expression) {
bool flag = true;
SeqStack<int> s(maxLength);
int j, length = strlen(expression);
for(int i =1; i<=length; i++) {
if(expression[i - 1] == '(') {
s.Push(i);
}
else if(expression[i - 1] == ')') {
//j用来存放Pop出的i值
if(s.Pop(j) == true) {
cout<<"("<<j<<","<<i<<")"<<endl;
}
else {
cout<<"没有与第"<<i<<"个右括号匹配的左括号"<<endl;
flag = false;
}
}
}
while(s.isEmpty() == false) {
s.Pop(j);
cout<<"没有与第"<<j<<"个左括号匹配的右括号"<<endl;
flag = false;
}
return flag;
}
int main() {
char* s = "1*((2+4)*3-5)-2)";
if(PrintMatchedPairs(s)) {
cout<<"bool"<<endl;
}
else {
cout<<"false"<<endl;
}
return 1;
}