Java教程

【基本数据结构实现】栈

本文主要是介绍【基本数据结构实现】栈,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

顺序栈

#include<iostream>
#include<exception>
using namespace std;

class BadSize: public exception
{
public:
    const char* what()const throw()
    {
        return "BAD SIZE!";
    }
};

class OutOfRange: public exception
{
public:
    const char* what()const throw()
    {
        return "OUT OF RANGE!";
    }
};

template<class T>
class Stack
{
private:
    T* stack;
    int top;
    int maxSize;
    void resize();
public:
    Stack(int initSize = 100);
    ~Stack() { delete[] stack; }
    bool isEmpty()const { return top == -1; }
    int size()const { return top + 1; }
    void clear()const { top = -1; }
    void push(const T& value);
    void pop();
    T getTop()const;
};

template<class T>
Stack<T>::Stack(int initSize)
{
    if (initSize < 0) throw BadSize();
    maxSize = initSize;
    stack = new T[maxSize];
    top = -1;
}

template<class T>
void Stack<T>::push(const T& value)
{
    if (top + 1 == maxSize) resize();
    stack[++top] = value;
}

template<class T>
void Stack<T>::pop()
{
    if (isEmpty()) throw OutOfRange();
    --top;
}

template<class T>
T Stack<T>::getTop()const
{
    if (isEmpty()) throw BadSize();
    return stack[top];
}

template<class T>
void Stack<T>::resize()
{
    T* auxStack = new T[maxSize * 2];
    for (int i = 0; i < maxSize; ++i)
    {
        auxStack[i] = stack[i];
    }
    maxSize *= 2;
    delete[] stack;
    stack = auxStack;
}


// test
int main()
{
    Stack<int> test(3);
    for (int i = 0; i < 5; ++i)
    {
        test.push(i);
    }
    for (int i = 0; i < 6; ++i)
    {
        test.pop();
        cout << test.getTop() << endl;
    }
}

 

这篇关于【基本数据结构实现】栈的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!