CareerCup-3.1

本文介绍了一种使用单一数组来实现三个栈的数据结构方法,并提供了两种不同的实现方案。第一种方案通过定义每个栈的起始位置来区分不同栈的空间;第二种方案则为每个元素附加了链表节点,用以跟踪栈顶元素。

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

Describe how you could use a single array to implement three stacks

Approach 1:

#include <iostream>
using namespace std;
#define SIZE 60
#define PERSIZE SIZE/3
typedef int Data;

class Stack
{
public:
    Stack(int type):mType(type)
    {
        if(type < 0 || type > 2)
        {
            throw "Error Stack Type";
        } else {
            tag = mType * PERSIZE - 1;
        }
    };
    void push(Data d)
    {
        if(tag >= (mType + 1) * PERSIZE - 1)
        {
            throw "Out of Size";
        } else {
            data[++tag] = d;
        }
    };
    void pop()
    {
        if(tag < mType * PERSIZE)
        {
            throw "Empty Stack";
        } else {
            tag --;
        }
    };
    Data peek()
    {
        if(tag < mType * PERSIZE)
        {
            throw "Empty Stack";
        } else {
            return data[tag];
        }
    };
    bool isEmpty(){return tag >= mType * PERSIZE;};
private:
    static Data data[SIZE];
    int mType;
    int tag;
};

Data Stack::data[SIZE];

Approach 2:

#include <iostream>
using namespace std;
#define SIZE 60
typedef int Data;

struct Node  
{
    Data data;  
    int next;  
};

class Stack
{
public:
    Stack(int type):mType(type)
    {
        if(type < 0 || type > 2)
        {
            throw "Error Stack Type";
        }
    };
    void push(Data d)
    {
        if(tag >= SIZE-1)
        {
            throw "Stack Full";
        }
        data[++tag].data = d;
        if(top[mType] < 0)
            data[tag].next = -1;
        else
            data[tag].next = top[mType];
        top[mType] = tag;
    };
    void pop()
    {
        if(top[mType] < 0)
        {
            throw "Empty Stack";
        }
        top[mType] = data[top[mType]].next;
        tag--;
    };
    Data peek()
    {
        if(top[mType] < 0)
        {
            throw "Empty Stack";
        } else {
            return data[top[mType]].data;
        }
    };
    bool isEmpty(){return top[mType] >= 0;};
private:
    static Node data[SIZE];
    int mType;
    static int top[3];
    static int tag;
};

Node Stack::data[SIZE];
int Stack::tag = -1;
int Stack::top[3] = {-1, -1, -1};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值