用1个array来建立3个stack。这里根据hawstein大大的文章来写。
Here it explains why Hawstein use this in his constructor, because he use size a parameter in his constructor while "size" is also a member variable(it's private), so he use this->size = size, explicitly define the member variable to be size.
Another solution is explicitly declare member variable with "m_", eg: m_size is a member variable, size is a parameter.
Cite from: http://www.learncpp.com/cpp-tutorial/87-the-hidden-this-pointer/
有问题还是应该躲在网上找找tutorial。上面这个网站就很好的解答了我的问题。
以下是完整代码:
// 3-1: describe 3 stacks by using single array
#include
using namespace std;
class stack3{
private:
int size;
int *buf;
int ptop[3];
public:
stack3(int size){
buf = new int[size*3];
ptop[0] = ptop[1] = ptop[2] = -1;
this->size = size;
}
~stack3(){
delete[] buf;
}
void pop(int stacknum){
//int pop(int stacknum){ // stacknum = 0,1,2
//int idx = stacknum*size + ptop[stacknum] + 1;
--ptop[stacknum];
//return buf[idx];
}
void push(int stacknum, int val){
int idx = stacknum*size + ptop[stacknum] + 1;
buf[idx] = val;
++ptop[stacknum];
}
int top(int stacknum){
int idx = stacknum*size+ptop[stacknum]; // no '+1'
return buf[idx];
}
bool empty(int stacknum){
return ptop[stacknum]==-1;
}
}; // note: need to add ';'
int main(){
stack3 jerry(10);
for(int i= 0; i<2; ++i){
jerry.push(0,i);
}
for(int i= 40; i<50; ++i){
jerry.push(1,i);
}
for(int i= 89; i<99; ++i){
jerry.push(2,i);
}
for(int i= 0; i<3; ++i){
cout << jerry.top(i) << "-t" << " stack: " << i<
output:
Executing the program....
$demo
1-t stack: 0
49-t stack: 1
98-t stack: 2
//empty吗?
0-e stack: 0
0-e stack: 1
0-e stack: 2
//
111 stack: 0
222 stack: 1
333 stack: 2
// pop 1次
1-t stack: 0
222-t stack: 1
333-t stack: 2
0-e stack: 0
0-e stack: 1
0-e stack: 2
// pop 2次
0-t stack: 0
222-t stack: 1
333-t stack: 2
0-e stack: 0
0-e stack: 1
0-e stack: 2
// pop 3次
0-t stack: 0
222-t stack: 1
333-t stack: 2
1-e stack: 0 // 终于空了,所以代码里面的idx改变要注意
0-e stack: 1
0-e stack: 2