栈的两种实现形式

栈的链表形式

#include <cstdio>
using namespace std;
#define null NULL
struct node{
    node* nxt;
    int val;
};
struct stack{
    node* head;
    int siz;//链表长度
    stack()   //构造函数,初始化
    {
        head = new node();
        siz = 0;
    void push(int val)
    {
        // head -> nodex -> nodex-1 -> ... ->NULL 
        node* cur = new node();
        cur->val =val;
        cur->nxt = head->nxt;
        head->nxt = cur;
        siz++;
    }
    void pop()
    {
        // head -> top(nodex) -> nodex-1 -> ... ->NULL
        node* top = head->nxt;
        head->nxt = top->nxt;
        delete top;
        siz--;
    }
    int top()
    {
        // head -> top(nodex) -> nodex-1 -> ... ->NULL
        if(siz > 0)//如果链表不为空,则返回栈顶元素
        {
            return head->nxt->val;
        }
        else
        {
            // error
            return 0;
        }
    }
    int size()
    {
        return siz;
    }
    bool empty()
    {
        return siz == 0;
    }
int main()
{
    stack st = stack();
    st.push(1);
    st.push(2);
    st.pop();
    st.push(3);
    st.push(10);
    st.push(5);
    st.pop();
    st.push(9);
    //9 10 3 1
    while(!st.empty())
    {
        int cur = st.top();
        st.pop();
        printf("%d\n",cur);//输出结果为 9 10 3 1
    }
}

栈的数组形式

#include <cstdio>
#define null NULL
using namespace std;
struct stack
{
    int* st;
    int _top;
    int siz;
    int maxSiz;
    stack(int msiz)
    {
        // st      st+1 st+2 ....     st+9 st+10
        // 1000    1001 1002 1003 ... 1009 1010
        // _bottom _top
        st = new int[msiz];// int st[10];
        _top = 0;
        siz = 0;
        maxSiz = msiz;
    }
    void push(int val)
    {
        if(siz == maxSiz)
        {
            printf("stack is full\n");
            return;
        }
        _top = (_top + 1) % maxSiz;
        st[_top] = val;
        siz++;
    }
    int top()
    {
        return st[_top];
    }
    void pop()
    {
        _top = (_top - 1 + maxSiz) % maxSiz;
        siz--;
    }
    bool empty()
    {
        return siz == 0;
    }
};
int main()
{
    stack st = stack(10);
    st.push(1);
    st.push(2);
    st.pop();
    st.push(3);
    st.push(10);
    st.push(5);
    st.pop();
    st.push(9);
    while(!st.empty())
    {
        int x =st.top();
        st.pop();
        printf("%d\n",x);//输出结果为9 10 3 1
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值