數據結構C++(4)棧——數組實現(arrayStack)


異常類 的 定義同 數據結構C++(2)線性表——vector實現(vectorList) 的 myExceptions.h 文件。

抽象基類 Stack 的定義 Stack.h :

 1 #pragma once
 2 
 3 template<typename T>
 4 class Stack  5 {  6 public:  7     virtual ~Stack() {} 8     virtual bool empty() const = 0;  9     virtual int size() const = 0; 10     virtual T &top() = 0; 11     virtual void pop() = 0; 12     virtual void push(const T &theElement) = 0; 13 };

類 arrayStack 的實現 arrayStack.h :

#pragma once #include <iostream> #include <sstream> #include <string> #include <ostream> #include <algorithm> #include "Stack.h" #include "myExceptions.h" template<typename T>
class arrayStack : public Stack<T> { public: arrayStack(int initLenth = 20); ~arrayStack(); bool empty() const; int size() const; T &top(); void pop(); void push(const T &theElement); protected: void changeLenth(T* &theElement, int oldLenth, int newLenth); T *stack; private: int stackTop; int stackSize; }; template<typename T> arrayStack<T>::arrayStack(int initLenth) { if (0 >= initLenth) { std::ostringstream s; s << "initLenth = " << initLenth << "must > 0" << endl; throw illegalParameterValue(s.str()); } stackTop = -1; stackSize = initLenth; stack = new T[initLenth]; } template<typename T> arrayStack<T>::~arrayStack() { delete [] stack; } template<typename T>
void arrayStack<T>::changeLenth(T* &theElement, int oldLenth, int newLenth) { if (newLenth < 0) { std::ostringstream s; s << "newLenth = " << newLenth << "must > 0" << endl; throw illegalParameterValue(s.str()); } T *Tmp = new T[newLenth]; int minux = min(oldLenth, newLenth); copy(theElement, theElement + minux, Tmp); delete[] theElement; theElement = Tmp; } template<typename T>
bool arrayStack<T>::empty() const { return stackTop == -1; } template<typename T>
int arrayStack<T>::size() const { return stackTop + 1; } template<typename T> T &arrayStack<T>::top() { if (-1 == stackTop) throw stackEmpty(); return stack[stackTop]; } template<typename T>
void arrayStack<T>::pop() { if (-1 == stackTop) throw stackEmpty(); stack[stackTop--].~T(); } template<typename T>
void arrayStack<T>::push(const T &theElement) { if (stackTop == stackSize - 1) { changeLenth(stack, stackSize, stackSize * 2); stackSize *= 2; } stack[++stackTop] = theElement; }

參考文獻:

[1].Sartaj Sahni. 數據結構、算法與應用[M]. 機械工業出版社, 2000.


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com