《CTCI》3.1 一个数组实现多个栈

《CITI》P131

3 栈与队列

题目:

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

解答:

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

#include <vector>

using namespace std;

struct stackNode
{
    int val;
    int preIndex;   //栈底结点为-2,无效结点为-1
    stackNode(int x = 0,int index = 0) :val(x), preIndex(index){}
};

class stacks
{
public:
    void push(int val, int index);
    void pop(int index);
    int top(int index);
    bool empty(int index);
    stacks(int count_);
    ~stacks();

private:
    vector<stackNode> stack;
    vector<int> topIndex;   //空栈为-2
    int count;
};

stacks::stacks(int count_)
{
    count = count_;
    for (int i = 0; i < count; i++)
        topIndex.push_back(-2);
}

stacks::~stacks()
{
    stack.clear();
    topIndex.clear();
}

void stacks::push(int val, int index)
{
    for (int i = 0; i < stack.size(); i++)
    {
        if (stack[i].preIndex == -1)
        {
            stack[i].val = val;
            stack[i].preIndex = topIndex[index];
            topIndex[index] = i;
            return;
        }
    }

    stackNode node(val, topIndex[index]);
    stack.push_back(node);
    topIndex[index] = stack.size()-1;
}

void stacks::pop(int index)
{
    if (empty(index))
        return;
    int temp = topIndex[index];
    topIndex[index] = stack[temp].preIndex;
    stack[temp].preIndex = -1;
}

int stacks::top(int index)
{
    if (empty(index))
        return -2;
    return stack[topIndex[index]].val;
}

bool stacks::empty(int index)
{
    return (topIndex[index] == -2);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值