顺序栈

来源:互联网 发布:桃花姬 知乎 编辑:程序博客网 时间:2024/04/24 18:21

 

#ifndef SEQSTACK_H

#define SEQSTACK_H

 

#include <iostream>

#include <assert.h>

using namespace std;

 

const int stackIncreament = 20;  //栈溢出时扩展空间的增量

 

template<class T>

class SeqStack

{

public:

     SeqStack(int sz = 50);

     ~SeqStack()

     {

         delete []elements;

     }

     void Push(const T &x); //如果栈满,刚溢出处理,否则把x插入到栈的栈顶

     bool Pop(T &x);    //如果栈空,则不执行退栈,返回false,否则退掉位于栈顶的元素,返回true

     bool GetTop(T &x); //如果栈空,则返回false,否则返回true,并通过x得到栈顶元素的值

     bool IsEmpty()const    //如果栈中元素个数等于,则返回true,否则返回false

     {

         return (top == -1) ? true : false;

     }

     bool IsFull()const //如果栈中元素个数等于maxSize,则返回true,否则返回false

     {

         return (top == maxSize - 1) ? true : false;

     }

     int GetSize()const //函数返回栈中元素个数

     {

         return top+1;

     }

     void MakeEmpty()   //清空栈的内容

     {

         top = -1;

     }

     template<class T>

     friend ostream& operator<<(ostream& os,SeqStack<T>& s); //输出栈中元素的重载操作

private:

     T *elements;  //存放栈中元素的数组

     int top; //栈顶指针

     int maxSize;  //栈最大可容纳元素的个数

     void overflowProcess(); //栈的溢出处理

};

 

template<class T>

SeqStack<T>::SeqStack(int sz /* = 50 */):top(-1),maxSize(sz)

{

     elements = new T[maxSize];

     assert(elements != NULL);

}

 

template<class T>

void SeqStack<T>::overflowProcess()

{

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

     assert(newArray != NULL);

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

         newArray[i] = elements[i];

     maxSize = maxSize + stackIncreament;

     delete elements;

     elements = newArray;

}

 

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;

     x = elements[top--];

     return true;

}

 

template<class T>

bool SeqStack<T>::GetTop(T &x)

{

     if(IsEmpty() == true)

         return false;

     x = elements[top];

     return true;

}

 

template<class T>

ostream& operator<<(ostream& os,SeqStack<T>& s)

{

     os<<"top="<<s.top<<endl;    //输出栈顶位置

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

         os<<i+1<<":"<<s.elements[i]<<endl;

     return os;

}

 

#endif