Describe how you could use a single array to implement three stacks.
#include <iostream>
#include <vector>
using namespace std;
const int STACK_SIZE = 20;
static vector<int> vec;
static int useful_len[3] = {STACK_SIZE, STACK_SIZE, STACK_SIZE};
bool push(int stack_no, int num)
{
if(useful_len[stack_no] == 0){
cout << "Stack " << stack_no << " overflow " << endl;
return false;
}
useful_len[stack_no] --;
vec.at(stack_no * STACK_SIZE + useful_len[stack_no]) = num;
return true;
}
bool pop(int stack_no, int &num)
{
if(useful_len[stack_no] == STACK_SIZE){
cout << "Stack " << stack_no << " underflow " << endl;
return false;
}
num = vec.at(stack_no * STACK_SIZE + useful_len[stack_no]);
useful_len[stack_no] ++;
return true;
}
bool peek(int stack_no, int &num)
{
if(useful_len[stack_no] == STACK_SIZE){
cout << "Stack " << stack_no << " is empty " << endl;
return false;
}
num = vec.at(stack_no * STACK_SIZE + useful_len[stack_no]);
return true;
}
int main(int argc, char* argv[])
{
vec.reserve(3 * STACK_SIZE);
vec.resize(3 * STACK_SIZE);
cout << "vector size is: " << vec.capacity() << endl;
for(int i = 0; i < 25; i++){
push(1, i);
}
int value;
for(int i = 0; i < 25; i++){
peek(1,value);
cout << "peek value: " << value << endl;
pop(1, value);
cout << "value: " << value << endl;
}
return 0;
}