首页 > 代码库 > C++学习笔记49:栈

C++学习笔记49:栈

栈是一种只能从一端访问的线性数据结构,栈是一种后进先出的数据结构

//stack.h
#ifndef STACK_H
#define STACK_H
#include <cassert>
template <class T, int SIZE = 50> class Stack
{
private:
    T list[SIZE];
    int top;
public:
    Stack();
    void push(const T &item);
    T pop();
    void clear();
    const T &peek() const;
    bool isEmpty() const;
    bool isFull() const;
};

//模板的实现
template <class T, int SIZE>
Stack<T, SIZE>::Stack():top(-1){}

template <class T, int SIZE> void Stack<T, SIZE>::push(const T &item)
{
    assert(!isFull());
    list[++top] = item;
}

template <class T, int SIZE> T Stack<T, SIZE>::pop() const
{
    assert(!isEmpty());
    return list[top--];
}

template <class T, int SIZE> const T &Stack<T, SIZE>::peek() const
{
    assert(!isEmpty());
    return list[top];
}

template <class T, int SIZE> bool Stack<T, SIZE>::isEmpty() const
{
    return top == -1;
}

template <class T, int SIZE> bool Stack<T, SIZE>::isFull() const
{
    return top == SIZE - 1;
}

template <class T, int SIZE> void Stack<T, SIZE>::clear()
{
    top = -1;
}

#endif // 

 

C++学习笔记49:栈