《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);
}