栈
链式存储.cpp和顺序存储.cpp
/* Stack.h */
#ifndef STACK_H
#define STACK_H
const int maxSize=50;
enum bool{false,true};
template<class T>
class Stack{
public:
Stack(){};
virtual void Push(const T &x)=0;
virtual bool Pop(T &x)=0;
virtual bool getTop(T &x)const=0;
virtual bool IsEmpty()const=0;
virtual bool IsFull()const=0;
virtual int getSize()const=0;
};
#endif
/* OrderStack.cpp */
#include<iostream.h>
#include<assert.h>
#include"Stack.h"
using namespace std;
const int OFSize=20;
template<class T>
class OrderStack:public Stack<T>{
protected:
T *elem;
int top;
int maxSize;
void OFsolution();
public:
OrderStack(int size=50);
~OrderStack(){delete []elem;}
void Push(const T&x);
bool Pop(T &x);
bool getTop(T &x)const;
bool IsFull()const{return (top==maxSize-1)?true:false;}
bool IsEmpty()const{return (top==-1)?true:false;}
int getSize()const{return top+1;}
void makeEmpty(){top=-1;}
friend ostream& operator<<(ostream& out,OrderStack<T> st);
};
OrderStack<T>::OrderStack(int size=50):top(-1),maxSize(size){
elem=new T[maxSize];
assert(elem!=NULL);
}
void OrderStack<T>::OFsolution(){
T *newArray=new T[maxSize+OFSize];
if(newArray==NULL){
cerr<<"allocate memory error"<<endl;
exit(1);
}
//move data
for(int i=0;i<=top;i++){
newArray[i]=elem[i];
}
maxSize=maxSize+OFSize;
delete []elem;
//evalute elem
elem=newArray;
}
void OrderStack<T>::Push(const T&x){
if(IsFull()==true){
OFsolution();
}
elem[top]=x;
top++;
}
bool OrderStack<T>::Pop(T &x){
if(IsEmpty()==true){
return false;
}
x=elem[top];
top--;
return true;
}
bool OrderStack<T>::getTop(T &x)const{
if(IsEmpty()==true)
return false;
x=elem[top];
return true;
}
ostream& OrderStack<T>::operator<<(ostream& out,OrderStack<T> st){
for(int i=0;i<=st.top;i++){
out<<st.elem[i]<<endl;
}
return out;
}
/* LinkStack.cpp */
#include<iostream.h>
#include"Stack.h"
#include"LinkList.h"
using namespace std;
template<class T>
class LinkStack:public Stack<T>{
public:
LinkStack():top(NULL){}
~LinkStack(){makeEmpty();}
void Push(const T &x);
bool Pop(T &x);
bool getTop(T &x)const;
bool IsEmpty()const{return (top==NULL)?true:false;}
int getSize()const;
void makeEmpty();
friend ostream& operator<< (ostream& out,LinkStack<T> &st);
protected:
LinkNode<T> *top;
}
template<class T>
void LinkStack<T>::makeEmpty(){
LinkNode<T> *p;
while(top!=NULL){
p=top;
top=top->link;
delete p;
}
}
template<class T>
void LinkStack<T>::Push(const T &x){
LinkNode<T> *newnode=new LinkNode<T>(x);
newnode->link=top;
top=newnode;
}
template<class T>
bool LinkStack<T>::Pop(T &x){
if(IsEmpty()){
return false;
}
x=top->elem;
top=top->link;
return true;
}
template<class T>
bool LinkStack<T>::getTop(T &x)const{
if(IsEmpty()){
return false;
}
x=top->elem;
return true;
}
template<class T>
int LinkStack<T>::getSize()const{
int ctr=1;
LinkNode<T> *p=top;
while(p!=NULL){
p=p->link;
ctr++;
}
return ctr;
}
template<class T>
ostream& LinkStack<T>::operator<< (ostream& out,LinkStack<T> &st){
LinkNode<T> *p=st.top;
while(p!=NULL){
out<<p->elem<<endl;
p=p->link;
}
return out;
}