Ch3-1: use a single array to implement three stacks.

用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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值