oral_quiz->#俩queue实现stack#

#include <stdio.h>
#include <queue>
#include <exception>
using namespace std;

template<typename T> class CStack {
public:
	CStack(void);
	~CStack(void);

	void appendTail(const T& node);
	T deleteHead();
private:
	queue<T> queue1;
	queue<T> queue2;
};

template<typename T> CStack<T>::CStack(void) {}
template<typename T> CStack<T>::~CStack(void) {}

template<typename T> void CStack<T>::appendTail(const T& node) {
	if(queue1.empty()) {
		queue2.push(node);
	}
	else {
		queue1.push(node);
	}
}

template<typename T> T CStack<T>::deleteHead() {
	if(!queue1.empty()) {
		while(queue1.size() > 1) {
			queue2.push(queue1.front());
			queue1.pop();
		}
		T& data = queue1.front();
		queue1.pop();
		return data;
	}
	else {
		while(queue2.size() > 1) {
			queue1.push(queue2.front());
			queue2.pop();
		}
		T& data = queue2.front();
		queue2.pop();
		return data;
	}
}

#include "Stack.h"

void Test(char actual, char expected) {
	if(actual == expected)
		printf("test passed.\n");
	else
		printf("test failed.\n");
}

int main(int argc, char* argv[]) {

	CStack<char> stack;

	stack.appendTail('a');
	stack.appendTail('c');
	stack.appendTail('d');
	stack.appendTail('f');

	Test(stack.deleteHead(), 'f');
	stack.appendTail('g');
	Test(stack.deleteHead(), 'g');
	Test(stack.deleteHead(), 'd');
	Test(stack.deleteHead(), 'c');
	Test(stack.deleteHead(), 'a');

	return 0;
}





你可能感兴趣的:(Queue,stack)