栈(数组实现)

1.思路
定义一个长度为N的数组arr,定义一个int len记录已存入数组的元素个数,入栈len++,出栈len–,len == 0栈空,len == N栈满。
2.代码

#include <iostream>
using namespace std;

struct Stack {
    int value;
    struct Stack *next;
};

Stack* CreateStack() {
    Stack* p = (Stack*)malloc(sizeof(Stack));
    p->value = 0;
    p->next = nullptr;

    return p;
}

bool isEmpty(Stack* p) {
    if(p == nullptr) {
        cout << "stack creats failed" << endl;
        return true;
    }
    return p->next == nullptr;
}

Stack* PushStack(Stack* p, int value) {
    if(p == nullptr) {
        cout << "stack creats failed" << endl;
        return nullptr;
    }
    Stack* tmp = (Stack*)malloc(sizeof(Stack));
    tmp->value = value;
    tmp->next = p->next;
    p->next = tmp;

    return p;
}

int PopStack(Stack* p) {
    if(p == nullptr) {
        cout << "stack creats failed" << endl;
        return -100000000;
    }
    Stack* tmp = p->next;
    p->next = tmp->next;
    int res = tmp->value;
    free(tmp);
    return res;
}

void Destroy(Stack* p) {
    while(!isEmpty(p)) {
        PopStack(p);
    }
    free(p);
    p = nullptr;
}

int main() {
    Stack* p = CreateStack();
    cout << "push 0-9" << endl;
    for(int i = 0; i < 10; ++i) {
        p = PushStack(p, i);
    }

    cout << "pop stack until it's empty" << endl;
    while(!isEmpty(p)) {
        cout << PopStack(p) << endl;
    }

    cout << "push 22" << endl;
    p = PushStack(p, 22);
    cout << "push 6" << endl;
    p = PushStack(p, 6);
    cout << "push 11" << endl;
    p = PushStack(p, 11);
    cout << "pop" << endl;
    cout << PopStack(p) << endl;
    cout << "pop" << endl;
    cout << PopStack(p) << endl;
    cout << "push 8" << endl;
    p = PushStack(p, 8);
    cout << "pop" << endl;
    cout << PopStack(p) << endl;
    cout << "pop" << endl;
    cout << PopStack(p) << endl;
    Destroy(p);

    return 0;
}

3.运行结果
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值