《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);
}
發佈了57 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章