用两个队列实现一个栈
2015-10-24 21:23
357 查看
queue.h
main.cpp
#include<iostream> #include<assert.h> using namespace std; template<typename T> struct Node { template<class T> friend class Queue; public: Node(const T& x) :_data(x) , _next(NULL) {} private: T _data; Node* _next; }; template<class T> class Queue { public: Queue() :_QHead(NULL) , _QTail(NULL) {} ~Queue() { while (_size != 0) { Node<T>* del = _QHead; _QHead = _QHead->_next; delete del; _size--; } } void Push(const T& x) //队尾插入元素 { assert(this); if (_QHead == NULL) { _QHead = new Node<T>(x); _QTail = _QHead; } else { Node<T>* tmp = new Node<T>(x); _QTail->_next = tmp; _QTail = tmp; } _size++; } void Pop() //队头删除元素 { assert(this); if (_QHead == NULL) //链表为空 { return; } if (_QHead == _QTail) //只有一个节点 { delete _QHead; _QHead = NULL; _QTail = NULL; } else //有多个节点 { Node<T>* del = _QHead; _QHead = _QHead->_next; delete del; } _size--; } bool Empty() //判空 { return _size == 0; } int Size() //返回队列长度 { return _size; } const T& Fornt() //返回队头元素 { return _QHead->_data; } const T& Back() //返回队尾元素 { return _QTail->_data; } private: Node<T>* _QHead; Node<T>* _QTail; size_t _size; };
main.cpp
#include"queue.h" template<class T> class Stack { public: Queue<T>* EmptyQ = &_p1; //指向空队列的指针 Queue<T>* NonEmptyQ = &_p2; //指向非空队列的指针 void Swap() { if (!EmptyQ->Empty()) //如果p1队列不为空,交换两个指针变量的值 { swap(EmptyQ, NonEmptyQ); } } void Push(const T& x) //哪个队列不是空的就往哪个队列插 { Swap(); NonEmptyQ->Push(x); _size++; } void Pop() { Swap(); size_t size = _size; while (size > 1) //把前_size - 1个数,挪到另外一个队列 { T tmp = NonEmptyQ->Fornt(); EmptyQ->Push(tmp); NonEmptyQ->Pop(); size--; } NonEmptyQ->Pop(); //删除最后一个元素 _size--; } bool Empty() { return _size == 0; } int Size() { return _size; } const T& Top() { Swap(); return NonEmptyQ->Back(); } private: Queue<T> _p1; Queue<T> _p2; size_t _size; }; void Test() { Stack<int> s1; s1.Push(1); s1.Push(2); s1.Push(3); s1.Pop(); s1.Push(4); s1.Top(); s1.Pop(); s1.Pop(); s1.Pop(); } int main() { Test(); getchar(); return 0; }
相关文章推荐
- VS2013无法进入断点进行调试
- LeetCode之Sqrt(x)
- lintcode- N皇后问题
- c# mybatis net +mysql 的一个初步摸索
- 利益相关者描述
- NOIP2000 方格取数
- 动态显示文件名之 Intent和Menu
- POJ3581:Sequence(后缀数组)
- (算法)求表达式(含括号)的值
- 今天你学到了啥?
- ubuntu输入密码后无法进入图形桌面
- 使用 Jni 调用 Dll 的实现JAVA在cmd控制台刷屏
- wordpress 后台取消显示custom fields(remove_meta_box)
- Android开发-控件
- Windows下如何查看被占用的端口号及如何释放被占用的端口号
- 2015-10-21 C#1
- ACM学习历程—HDU 5073 Galaxy(数学)
- 夺命雷公狗---无限级分类NO4
- HDU3584Cube(三维树状数组)
- 1024杂项1