栈与队列相关习题

题目:
用一个数组表示队列,只有front指针,没有rear指针,用count计数,实现pop操作。

template <class T>
class Queue {
	private:
		int count;
		T *front;
	public:
		Queue(int m = 0);
		~Queue();
		bool pop();
};

Queue<T>::Queue(int m = 0) {
	count = 0;
	m && front = new T[m];
}

Queue<T>::~Queue() {
	delete [] front;
}

bool Queue<T>::pop() {
	if(count == 0) {
		std::cout << "Queue is full" << endl;
		return false;
	}
	for(int i = 0; i < count-1; ++i) {
		front[i] = front[i+1];
	} 
	--count;
	return true;
}

题目:
假设以带头结点的循环链表表示队列,并且只设一个指针指向队尾元素(不设头结点),编写相应的入队函数。

void push(const T & item) {
	Link<T>* tmp = new Link<T>(item); 
	tmp->next = tail->next;
	tail->next = tmp;
	tail = tail->next;
}

题目:
在一个长度为n的数组中实现两个栈,(总元素不超过n),保证push和pop为O(1)时间

分析:有两种方式:
1.将数组的两端看成栈底,同时向中间延伸
2.将数组的中间看成栈底,向数组两边延伸

这两种比较的话,明显第一种方式更加优秀。因为第二种限制了每个栈的上限为n/2,如果一个栈元素多于n/2,另一个少于n/2,那么第二种方式栈溢出,第一种方式可以存储。因此,下面实现方式1.

template <class T>
class DoubleStack {
	private:
		T *p;
		int sp1,sp2;
		int size1,size2;
		int totalLength;
	public:
		DoubleStack(int n) {
			totalLength = n;
			p = new T[n];
			sp1 = 0;
			sp2 = n-1;
			size1 = 0;
			size1 = 0;
		}
		~DoubleStack() {
			delete [] p;
		}
		void pushLift(const T & item);
		void pushRight(const T & item);
		void popLift();
		void popRigth();
};

void DoubleStack::pushLift(const T & item) {
	if(sp1 == sp2) throw overflow_error;
	p[sp1] = item;
	sp++;
	size1++;
}

void DoubleStack::pushRight(const T & item) {
	if(sp1 == sp2) throw overflow_error;
	p[sp2] = item;
	sp--;
	size1++;
}

void DoubleStack::popLift() {
	if(sp1 == 0) throw out_of_range;
	sp1--;
	size1--;
}

void DoubleStack::popLift() {
	if(sp2 == totalLength-1) throw out_of_range;
	sp2++;
	size1--;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值