Q:Describe how you could use a single array to implement three stacks
A:
思路一:比较直观的想法是将一个数组分为三部分。将数组平分三部分, 每个部分维护一个栈顶指针。对特定的栈进行操作只要用栈顶指针加上偏移量就可以。
思路二:思路一可能会浪费大量的空间。所以不均分数组为三部分。定义一种数据类型,可以记录当前元素值和上一个元素的位置。
#include <iostream>
using namespace std;
class stack3_1{
private:
int *buf;
int size;
int ptop[3];
public:
stack3_1(int size = 100) {
this->size;
buf = new int(size*3);
ptop[0]=ptop[1]=ptop[2]=-1;
}
~stack3_1() {
delete[] buf;
}
void push(int num, int val) {
int ind = num*size + ptop[num] + 1;
buf[ind] = val;
ptop[num]++;
}
void pop(int num) {
ptop[num]--;
}
int top(int num) {
int ind = num*size + ptop[num];
return buf[ind];
}
bool empty(int num) {
return ptop[num] == -1;
}
};
typedef struct node {
int val;
int preInd;
node():val(0),preInd(-2){
};
}node;
class stack3_2{
private:
node *buf;
int size;
int cur;
int ptop[3];
public:
stack3_2(int size = 300) {
this->size = size;
buf = new node[size];
ptop[0]=ptop[1]=ptop[2]=-1;
cur = 0;
}
~stack3_2() {
delete[] buf;
}
void push(int num, int val) {
buf[cur].val = val;
buf[cur].preInd = ptop[num];
ptop[num] = cur;
while (cur < this->size && buf[cur].preInd != -2) {
cur++;
}
}
void pop(int num) {
if (cur > ptop[num]) {
cur = ptop[num];
}
int ind = buf[ptop[num]].preInd;
buf[ptop[num]].preInd = -2;
ptop[num] = ind;
}
int top(int num) {
return buf[ptop[num]].val;
}
bool empty(int num) {
return ptop[num] == -1;
}
};
int main(){
stack3_2 mystack;//stack3 mystack;
for(int i=0; i<10; ++i)
mystack.push(0, i);
for(int i=10; i<20; ++i)
mystack.push(1, i);
for(int i=100; i<110; ++i)
mystack.push(2, i);
for(int i=0; i<3; ++i)
cout<<mystack.top(i)<<" ";
cout<<endl;
for(int i=0; i<3; ++i){
mystack.pop(i);
cout<<mystack.top(i)<<" ";
}
mystack.push(0, 111);
mystack.push(1, 222);
mystack.push(2, 333);
for(int i=0; i<3; ++i)
cout<<mystack.top(i)<<" ";
return 0;
}