编程语言
首页 > 编程语言> > C++数据结构之栈(十三)

C++数据结构之栈(十三)

作者:互联网

栈是一种后进先出(Last in / First out, LIFO)的数据结构。


栈的主要操作有以下几种:


在这里插入图片描述参考博客:https://www.cnblogs.com/msymm/p/9751326.html
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

测试.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;
}

使用标准库的栈和队列时,先包含相关的头文件

#include<stack>
定义栈如下:
stack<int> s;
s.empty() 如果栈为空返回true,否则返回false
s.size() 返回栈中元素的个数
s.pop() 删除栈顶元素
s.top() 返回栈顶的元素
s.push() 在栈顶压入新元素

C++ 语言: STL 自带的“栈”(stack)的示例。

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

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;
}

标签:arr,int,istack,之栈,栈顶,C++,ArrayStack,push,数据结构
来源: https://blog.csdn.net/qq_32642107/article/details/100940998