面试题 03.01. Three in One LCCI

Problem

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

Yout should implement push(stackNum, value)、pop(stackNum)、isEmpty(stackNum)、peek(stackNum) methods. stackNum is the index of the stack. value is the value that pushed to the stack.

The constructor requires a stackSize parameter, which represents the size of each stack.

Example1

Input:
[“TripleInOne”, “push”, “push”, “pop”, “pop”, “pop”, “isEmpty”]
[[1], [0, 1], [0, 2], [0], [0], [0], [0]]
Output:
[null, null, null, 1, -1, -1, true]
Explanation: When the stack is empty, pop, peek return -1. When the stack is full, push does nothing.

Example2

Input:
[“TripleInOne”, “push”, “push”, “push”, “pop”, “pop”, “pop”, “peek”]
[[2], [0, 1], [0, 2], [0, 3], [0], [0], [0], [0]]
Output:
[null, null, null, null, 2, 1, -1, -1]

Solution

直观解法,将数组vec均分成3块。
iss数组的元素用于记录每个栈的顶,底和栈针。

class TripleInOne {
public:
    TripleInOne(int stackSize) {
        int vec_size = 3 * stackSize;
        vec.resize(vec_size);
        for(int i = 0;i<3;++i)
        {
            inner_stack s;
            s.bottom = 0 + i * stackSize;
            s.top = 0 + (i+1) * stackSize;
            s.cur = s.bottom-1;

            iss.push_back(s);
        }

    }
    
    void push(int stackNum, int value) {
        if(iss[stackNum].cur < iss[stackNum].top - 1)
        {
            iss[stackNum].cur++;
            vec[iss[stackNum].cur] = value;  
        }
    }
    
    int pop(int stackNum) {
        if(iss[stackNum].cur >= iss[stackNum].bottom && iss[stackNum].cur < iss[stackNum].top)
        {
            int ret = vec[iss[stackNum].cur];
            iss[stackNum].cur--;
            return ret;

        }
        else
        {
            return -1;
        }

    }
    
    int peek(int stackNum) {
        if(iss[stackNum].cur >= iss[stackNum].bottom && iss[stackNum].cur < iss[stackNum].top)
        {
            int ret = vec[iss[stackNum].cur];
            return ret;

        }
        else
        {
            return -1;
        }
    }
    
    bool isEmpty(int stackNum) {
        return iss[stackNum].cur == iss[stackNum].bottom - 1;

    }

    struct inner_stack
    {
        int bottom;
        int top;
        int cur;
    };

    vector<int> vec;
    vector<inner_stack> iss;



};

/**
 * Your TripleInOne object will be instantiated and called as such:
 * TripleInOne* obj = new TripleInOne(stackSize);
 * obj->push(stackNum,value);
 * int param_2 = obj->pop(stackNum);
 * int param_3 = obj->peek(stackNum);
 * bool param_4 = obj->isEmpty(stackNum);
 */
发布了526 篇原创文章 · 获赞 215 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105130055
今日推荐