栈的实现——c++

栈(stack),是一种线性存储结构,它有以下几个特点:
  (01) 栈中数据是按照"后进先出(LIFO, Last In First Out)"方式进出栈的。
  (02) 向栈中添加/删除数据时,只能从栈顶进行操作。

栈通常包括的三种操作:push、peek、pop
  push -- 向栈中添加元素。
  peek -- 返回栈顶元素。
  pop  -- 返回并删除栈顶元素的操作

C++的STL中本身就包含了stack类,基本上该stack类就能满足我们的需求,所以很少需要我们自己来实现。本部分介绍2种C++实现。
1. C++实现一:数组实现的栈,能存储任意类型的数据。
2. C++实现二:C++的 STL 中自带的"栈"(stack)的示例。

1. C++实现一:数组实现的栈,能存储任意类型的数据

实现代码:.h

#ifndef ARRAY_STACK_HXX
#define ARRAY_STACK_HXX

#include <iostream>
#include "ArrayStack.h"
using namespace std;

template<class T> class ArrayStack{
    public:
        ArrayStack();
        ~ArrayStack();

        void push(T t);
        T peek();
        T pop();
        int size();
        int isEmpty();
    private:
        T *arr;
        int count;
};

// 创建“栈”,默认大小是12
template<class T>
ArrayStack<T>::ArrayStack() 
{
    arr = new T[12];
    if (!arr) 
    {
        cout<<"arr malloc error!"<<endl;
    }
}

// 销毁“栈”
template<class T>
ArrayStack<T>::~ArrayStack() 
{
    if (arr) 
    {
        delete[] arr;
        arr = NULL;
    }
}

// 将val添加到栈中
template<class T>
void ArrayStack<T>::push(T t) 
{
    //arr[count++] = val;
    arr[count++] = t;
}

// 返回“栈顶元素值”
template<class T>
T ArrayStack<T>::peek() 
{
    return arr[count-1];
}

// 返回“栈顶元素值”,并删除“栈顶元素”
template<class T>
T ArrayStack<T>::pop() 
{
    int ret = arr[count-1];
    count--;
    return ret;
}

// 返回“栈”的大小
template<class T>
int ArrayStack<T>::size() 
{
    return count;
}

// 返回“栈”是否为空
template<class T>
int ArrayStack<T>::isEmpty()
{
    return size()==0;
}

#endif
View Code

测试代码:.cpp

#include <iostream>
#include "ArrayStack.h"
using namespace std;

int main() 
{
    int tmp=0;
    ArrayStack<int> *astack = new ArrayStack<int>();

    cout<<"main"<<endl;

    // 将10, 20, 30 依次推入栈中
    astack->push(10);
    astack->push(20);
    astack->push(30);

    // 将“栈顶元素”赋值给tmp,并删除“栈顶元素”
    tmp = astack->pop();
    cout<<"tmp="<<tmp<<endl;

    // 只将“栈顶”赋值给tmp,不删除该元素.
    tmp = astack->peek();

    astack->push(40);

    while (!astack->isEmpty())
    {
        tmp = astack->pop();
        cout<<tmp<<endl;
    }

    return 0;
}
View Code

结果说明:关于"栈的声明和实现都在头文件中"的原因,是因为栈的实现利用了C++模板,而"C++编译器不能支持对模板的分离式编译"。这在"数据结构和算法01之 线性表"中已经介绍过了。  程序的实现和逻辑都非常简单。需要说明的是,采用C++模板实现的;但是,默认数组的大小只有12,而且该实现不支持动态扩展。

2. C++实现二:C++的 STL 中自带的"栈"(stack)的示例

实现代码:

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

/**
 * C++ 语言: STL 自带的“栈”(stack)的示例。
 *
 * @author skywang
 * @date 2013/11/07
 */
int main ()
{
    int tmp=0;
    stack<int> istack;

    // 将10, 20, 30 依次推入栈中
    istack.push(10);
    istack.push(20);
    istack.push(30);

    // 将“栈顶元素”赋值给tmp,并删除“栈顶元素”
    istack.pop();

    // 只将“栈顶”赋值给tmp,不删除该元素.
    tmp = istack.top();

    istack.push(40);

    while (!istack.empty())
    {
        tmp = istack.top();
        istack.pop();
        cout<<tmp<<endl;
    }

    return 0;
}
View Code

本文来自http://www.cnblogs.com/skywang12345/p/3562239.html

原文地址:https://www.cnblogs.com/msymm/p/9751326.html