C++不用STL实现栈

本文介绍了如何使用C++编写一个类来实现栈,包括构造函数、扩容方法、基本操作如push、pop以及检查栈是否为空和获取栈大小的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*用C++的类写的栈比C好在:
1.代码层面:1.除了Push,其他不用传参了
            2.调用栈的属性不用先通过结构体找属性->找了
            3.函数直接写在类里面要用直接调类
            4.构造函数可以缺省参数,提供选择,
2.调用直接.找成员,不用考虑怎么传指针,当作变量使用即可
注意:(不足)
栈方法得写:1.栈是否为空
            2.栈的大小
            (因为size是私有的,外部无接口查看)
*/
#include<iostream>
#include<stdlib.h>
#include<assert.h>
using namespace std;
//stack
typedef int StackDataType;
class Stack
{
    StackDataType* array=nullptr;
    int capacity = 0;
    int size = 0;
public:
    Stack(int num_array = 0)
    {
        if (num_array)
        {
            StackDataType* ptr = (StackDataType*)malloc(sizeof(StackDataType) * num_array);
            if (ptr == nullptr)
                perror("malloc");
            array = ptr;
        }
    }
    ~Stack()
    {
        free(array);
        array = nullptr;
    }
    bool StackExpansion()
    {
        if (size == capacity)
        {
            int newcapacity = capacity == 0 ? 4 : capacity * 2;
            StackDataType* newptr = (StackDataType*)realloc(array, sizeof(StackDataType) * newcapacity);
            if (newptr)
            {
                array = newptr;
                capacity = newcapacity;
            }
            else
            {
                perror("StackExpansion");
                return false;
            }
        }
        return true;
    }
    void StackPush(StackDataType x)
    {
        if (!StackExpansion())
        {
            perror("StackPush");
            return;
        }
        array[size++] = x;
    }
    void StackPop()
    {
        assert(size);
        size--;
    }
    StackDataType StackTop()
    {
        assert(size);
        return array[size - 1];
    }
    //判断是否为空
    bool StackIsEmpty()
    {
        return size == 0;
    }
    //返回栈数据个数
    int StackSize()
    {
        return size;
    }
};
int main()
{
    Stack stack(4);
    int array[10] = { 1,2,3,4,5,6,7,8,9,10 };
    for (int& e : array)
    {
        stack.StackPush(e);
    }
    while (!stack.StackIsEmpty())
    {
        cout << stack.StackTop()<<" ";
        stack.StackPop();
    }
    cout << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值