数据结构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.


免责声明!

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



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM