[CareerCup] 3.1 Implement Three Stacks using Array 使用数组来实现三个栈

简介:

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

这道题让我们用一个数组来实现三个栈,书上给了两种方法,第一种方法是定长分割 Fixed Division,就是每个栈的长度相同,用一个公用的一位数组buffer来保存三个栈的内容,前三分之一为第一个栈,中间三分之一为第二个栈,后三分之一为第三个栈,然后还要分别记录各个栈当前元素的个数,然后再分别实现栈的基本操作push, pop, top 和 empty,参见代码如下:

class ThreeStacks {
public:
    ThreeStacks(int size) : _stackSize(size) {
        _buffer.resize(size * 3, 0);
        _stackCur.resize(3, -1);
    }
    
    void push(int stackIdx, int val) {
        if (_stackCur[stackIdx] + 1 >= _stackSize) {
            cout << "Stack " << stackIdx << " is full!" << endl;
        }
        ++_stackCur[stackIdx];
        _buffer[stackIdx * _stackSize + _stackCur[stackIdx]] = val;
    }
    
    void pop(int stackIdx) {
        if (empty(stackIdx)) {
            cout << "Stack " << stackIdx << " is empty!" << endl;
        }
        _buffer[stackIdx * _stackSize + _stackCur[stackIdx]] = 0;
        --_stackCur[stackIdx];
    }
    
    int top(int stackIdx) {
        if (empty(stackIdx)) {
            cout << "Stack " << stackIdx << " is empty!" << endl;
        }
        return _buffer[stackIdx * _stackSize + _stackCur[stackIdx]];
    }
    
    bool empty(int stackIdx) {
        return _stackCur[stackIdx] == -1;
    }
    
private:
    int _stackSize;
    vector<int> _buffer;
    vector<int> _stackCur;
};

本文转自博客园Grandyang的博客,原文链接:使用数组来实现三个栈[CareerCup] 3.1 Implement Three Stacks using Array ,如需转载请自行联系原博主。

相关文章
|
2月前
|
Python
使用array()函数创建数组
使用array()函数创建数组。
29 3
|
2月前
|
JavaScript 前端开发
总结TypeScript 的一些知识点:TypeScript Array(数组)(下)
一个数组的元素可以是另外一个数组,这样就构成了多维数组(Multi-dimensional Array)。
|
2月前
|
存储 JavaScript 前端开发
总结TypeScript 的一些知识点:TypeScript Array(数组)(上)
数组对象是使用单独的变量名来存储一系列的值。
|
9天前
|
存储 安全 算法
C++的内置数组和STL array、STL vector
C++的内置数组和STL array、STL vector
|
2月前
|
JavaScript 前端开发 索引
在JavaScript中,可以使用数组字面量或Array构造函数来创建一个数组对象
【4月更文挑战第16天】在JavaScript中,可以使用数组字面量或Array构造函数来创建一个数组对象
31 4
|
2月前
|
存储 索引 Python
多数pythoneer只知有列表list却不知道python也有array数组
多数pythoneer只知有列表list却不知道python也有array数组
34 0
|
2月前
|
存储 缓存 安全
【C/C++ 基础 数组容器比较】深入探究C++容器:数组、vector与array之间的异同
【C/C++ 基础 数组容器比较】深入探究C++容器:数组、vector与array之间的异同
49 0
|
2月前
|
Rust 索引 Windows
Rust 原始类型之数组array内置方法
Rust 原始类型之数组array内置方法
95 0
Rust 原始类型之数组array内置方法
|
2月前
Google Earth Engine(GEE)——reducer中进行array数组的获取和分析
Google Earth Engine(GEE)——reducer中进行array数组的获取和分析
173 0
|
2月前
|
存储 索引 Python
python中的数组(Array)
python中的数组(Array)
29 0