1. 栈和队列的数组实现

  • 用数组实现一个栈

    栈顶元素下标index与其对应的数组元素下标f(index)之间的映射关系是怎样的?随着栈的增长,栈顶元素下标依次为0,1,2...n-1,其中n表示栈的最大高度。我们需要制定一种映射规则f,方便我们通过index计算出f(index)。而最简单的规则就是f(index) = index。

    都需要记录哪些信息?数组本身的指针p、总长度SIZE,以及栈顶元素下标index。

#include<iostream>
template<typename Object>
class Stack
{
public:
    Stack()
    {
        init();
    }
    Stack(const Stack& rhs)
    {
        init();
        index = rhs.index;
        for(int i = 0; i != index + 1; ++i)
            p[i] = rhs.p[i];
    }

    Stack(Stack&& rhs):p(rhs.p),index(rhs.index)
    {
        rhs.p = nullptr;
        rhs.index = -1;
    }

    Stack& operator =(const Stack& rhs)
    {
        Stack copy(rhs);
        std::swap(p, copy.p);
        std::swap(index, copy.index);
        return *this;
    }

    Stack& operator =(Stack&& rhs)
    {
        std::swap(p, rhs.p);
        std::swap(index, rhs.index);
        return *this;
    }

    ~Stack()
    {
        if(p)
            delete[] p;
    }

    void push(const Object& object)
    {
        if(index == MAX_SIZE-1)
            std::cerr << "overflow" << std::endl;
        else
            p[++index] = object;
    }

    void push(Object&& object)
    {
        if(index == MAX_SIZE-1)
            std::cerr << "overflow" << std::endl;
        else
            p[++index] = std::move(object);
    }
    void pop()
    {
        if(empty())
            std::cerr << "underflow" << std::endl;
        else
            --index;
    }
    Object& top()
    {
        return p[index];
    }
    const Object& top() const
    {
        return p[index];
    }
    bool empty() const
    {
        return index == -1;
    }
private:
    static constexpr int MAX_SIZE = 4;
    Object* p;
    int     index;

    void init()
    {
        p = new Object[MAX_SIZE];
        index = -1;
    }
};

猜你喜欢

转载自www.cnblogs.com/meixiaogua/p/10167635.html