码迷,mamicode.com
首页 > 其他好文 > 详细

用栈实现队列的效果

时间:2014-09-15 22:56:39      阅读:481      评论:0      收藏:0      [点我收藏+]

标签:

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

实现的栈基本功能

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 = data;
		node->m_next = m_top;
		m_top = node;*/
		m_top = new Node (data, m_top);
	}
	// 弹出
	int pop (void) {
		if (empty ())
			throw UnderFlow ();
		int data = m_top->m_data;
		Node* next = m_top->m_next;
		delete m_top;
		m_top = next;
		return data;
	}
	// 判空
	bool empty (void) const {
		return ! m_top;
	}
private:
	// 下溢异常
	class UnderFlow : public exception {
		const char* what (void) const throw () {
			return "堆栈下溢!";
		}
	};
	// 节点
	class Node {
	public:
		Node (int data = 0, Node* next = NULL) :
			m_data (data), m_next (next) {}
		int m_data; // 数据
		Node* m_next; // 后指针
	};
	Node* m_top; // 栈顶
};
#endif // _LSTACK_H

实现的队列:

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


用栈实现队列的效果

标签:

原文地址:http://blog.csdn.net/liyuan_669/article/details/39298869

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!