栈的原理及简单实现

196 阅读2分钟

本文已参与[新人创作礼]活动,一起开启掘金创作之路
栈的原理: 栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。 栈是 后进先出(last-in,first-out LIFO),如果怕与之后要讲的队列混淆,可以记住stack.pop,也就是栈是弹出的,也就是从顶端弹出,就像是手枪子弹上膛一样,最后上膛的子弹总是最先出膛(Pop)。 下面是基于C++实现的栈,其中top指向栈顶的位置

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;

//采用模板的形式,方便复用
//top == -1 表示栈为空
template<class T>
class MyStack{
public:
    MyStack(int size);
    ~MyStack();//析构函数,销毁数据,减少数据占用
    string Push(T value);//因为C++中 true是返回1 false返回0 不直观,因此返回字符串
    int Pop(T &ele);//返回当前top的值,ele为弹出的元素值
    int GetCurrentLength();//返回当前栈的有效长度,并非length
private:
    bool IsEmpty();
    bool IsFull();
    int length;
    T *stk;//模板T的数组
    int top;
    string strTrue;//用于返回true的字符串
    string strFalse;//用于返回false的字符串
};


template<class T>
MyStack<T>::MyStack(int size):length(size)
{
    stk = new T[size];
    top = -1;
    strTrue = "true";
    strFalse = "false";
}


template<class T>
MyStack<T>::~MyStack()
{
    length = 0;
    delete stk;
    top = -1;
}


template<class T>
string MyStack<T>::Push(T value)
{
    if (IsFull() == false)
    {
        stk[++top] = value;
        cout<<"入栈"<<value<<" top="<<top<<endl;
        return strTrue;
    }
    cout<<"栈满了"<<endl;
    return strFalse;
}

//&其次这个形参是一个引用
template<class T>
int MyStack<T>::Pop(T &ele)
{
   if (IsEmpty() == false)
   {
       ele = stk[top--];
   }
   else
       cout<<"栈空了"<<endl;
   return top;
}


template<class T>
bool MyStack<T>::IsEmpty()
{
    return top == -1;
}

template<class T>
bool MyStack<T>::IsFull()
{
    return top == (length-1);
}

template<class T>
int MyStack<T>::GetCurrentLength()
{
    return top+1;
}

int main()
{
    MyStack<int> stk(6);
    //true 的话返回是1
    cout<<stk.Push(3)<<endl;
    cout<<stk.Push(2)<<endl;
    cout<<stk.Push(1)<<endl;
    cout<<stk.GetCurrentLength()<<endl;
    int temp,currentLength;
    for (int i=4;i>0;i--)
    {
        currentLength = stk.Pop(temp);
        cout<<"当前出栈的值为"<<temp<<",当前栈top指向"<<currentLength<<endl;
    }
}

运行结果如下 在这里插入图片描述