c++顺序栈

主文件

#include

#include "SeqStack.h"

int main()

{

int i1=10,i2=20,i3=30,i4;

SeqStack s1;

s1.Push(i1);s1.Push(i2);s1.Push(i3);

s1.output();

s1.Pop(i4);

s1.output();

return 0;

}

头文件

//SeqStack.h:interface for the SeqStack class

#if !defined _SEQSTACK_H_

#define _SEQSTACK_H_

#include

const int stackIncreasement=20;

template

class SeqStack

{

public:

SeqStack(int sz=50);

~SeqStack(){};

void Push(const T&x);

bool Pop(T &x);

bool getTop(T &x);

bool IsEmpty()const{return (top==-1)?true:false;}

bool IsFull()const{return (top==maxSize-1)?true:false;} int getSize()const{return top+1;}

void MakeEmpty(){top=-1;}

void output();

private:

T *elements;

int top;

int maxSize;

void overflowProcess();

};

template

SeqStack::SeqStack(int sz):top(-1),maxSize(sz)

{

elements=new T[maxSize];

assert(elements!=NULL);

}

template

void SeqStack::overflowProcess()

{

T *newArray=new T[maxSize+stackIncreasement];

if(newArray==NULL)return ;

for(int i=0;i<=top;i++)newArray[i]=elements[i];

maxSize=maxSize+stackIncreasement;

delete []elements;

elements=newArray;

}

template

void SeqStack::Push(const T&x)

{

if(IsFull()==true)overflowProcess();

elements[++top]=x;

}

template

bool SeqStack::Pop(T &x)

{

if(IsEmpty()==true)return false;

x=elements[top--];

return true;

}

template

bool SeqStack::getTop(T &x)

{

if(IsEmpty()==true)return false;

x=elements[top];

return true;

}

template

void SeqStack::output()

{

for(int i=0;i<=top;i++)

cout<

}

#endif

相关文档
最新文档