Q3.1 Describe how you could use a single array to implement three stacks

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值