首页 > 代码库 > 用栈实现队列的效果

用栈实现队列的效果

用两个栈实现队列的效果,可以入栈,出栈,判空等。。。

实现的栈基本功能

lstack.h

#ifndef _LSTACK_H
#define _LSTACK_H
#include <stdexcept>
using namespace std;
// 基于链式表的堆栈
class Stack {
public:
	// 构造过程中初始化为空堆栈
	Stack (void) : m_top (NULL) {}
	// 析构过程中销毁剩余的节点
	~Stack (void) {
		for (Node* next; m_top; m_top = next) {
			next = m_top->m_next;
			delete m_top;
		}
	}
	// 压入
	void push (int data) {
		/*
		Node* node = new Node;
		node->m_data = http://www.mamicode.com/data;>

实现的队列:

squeue.cpp

#include <iostream>
#include "lstack.h"
using namespace std;
// 基于堆栈的队列
class Queue {
public:
	// 压入
	void push (int data) {
		m_i.push (data);
	}
	// 弹出
	int pop (void) {
		if (m_o.empty ()) {
			if (m_i.empty ())
				throw underflow_error("队列下溢!");
			while (! m_i.empty ())
				m_o.push (m_i.pop ());
		}
		return m_o.pop ();
	}
	// 判空
	bool empty (void) const {
		return m_i.empty () && m_o.empty ();
	}
private:
	Stack m_i; // 输入栈
	Stack m_o; // 输出栈
};
int main (void) {
	try {
		Queue queue;
		for (int i = 0; i < 10; ++i)
			queue.push (i);
		cout << queue.pop () << endl; // 0
		cout << queue.pop () << endl; // 1
		cout << queue.pop () << endl; // 2
		cout << queue.pop () << endl; // 3
		cout << queue.pop () << endl; // 4
		queue.push (10);
		queue.push (11);
		queue.push (12);
		while (! queue.empty ())
			cout << queue.pop () << endl;
	}
	catch (exception& ex) {
		cout << ex.what () << endl;
		return -1;
	}
	return 0;
}


用栈实现队列的效果