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

转载于:https://www.cnblogs.com/peformer/p/8029130.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值