我的简单链式队列
最近老师要我们写一个二叉树的结构,并且用程序将它实现。我想这是一个好时机,我就开始写一个二叉树了。当然,我写二叉树的意图不是要给老师看的,而是想要为自己的游戏编程添砖加瓦。所以我从星期一的下午开始就开始研究二叉树的结构,一直到了今天。还没有做完。
今天研究二叉树的层序遍历的时候,我一直想不出怎样遍历。后来上网查了资料,它必须使用队列这种结构。我想到了自己以前写的队列。但是打开电脑一看,竟然是顺序存储形式的队列。这怎么行呢?如果是顺序的话,肯定要浪费空间的,而且操作比较繁琐,需要臆想一个循环的队列,并且需要考虑是否“假”溢出的问题。基于以上的顾虑,我还是重新写一个我自己的队列,它的存储结构是链式的,这样的话会缓解上述问题。并且更容易理解。说做就做,我今天花了一个小时开始调试了我的简单队列。下面就是我的队列的代码:
- #ifndef _JCHAINQUEUE_H_
- #define _JCHAINQUEUE_H_
- // 链式队列节点结构体
- template <typename CustomType>
- struct JQueueNode
- {
- JQueueNode():link(0){}// 默认构造函数
- ~JQueueNode(){}// 默认析构函数
- CustomType elem;
- JQueueNode* link;
- };
- // 链式队列类
- template <typename CustomType>
- class JChainQueue
- {
- public:
- JChainQueue():front(0), rear(0){}// 默认构造函数
- ~JChainQueue(){}// 默认析构函数
- bool EnterQueue( CustomType obj );// 将元素压入队列
- CustomType DeleteQueue( void );// 将队列头元素弹出
- bool IsEmpty( void );// 判断队列是否为空
- CustomType GetFront( void );// 取出队列头元素
- private:
- JQueueNode<CustomType>* front;
- JQueueNode<CustomType>* rear;
- };
- // 将元素压入队列
- template <typename CustomType>
- bool JChainQueue<CustomType>::EnterQueue( CustomType obj )
- {
- if ( rear == 0 )
- front = rear = new JQueueNode<CustomType>;// 初始化
- rear->elem = obj;
- rear->link = new JQueueNode<CustomType>;
- rear = rear->link;
- return true;
- }
- // 将队列头元素弹出
- template <typename CustomType>
- CustomType JChainQueue<CustomType>::DeleteQueue( void )
- {
- JQueueNode<CustomType> temp;
- if ( IsEmpty() ) return temp.elem; // 加入了安全的措施(更新于10月10日21:34)
- temp.elem = front->elem;
- temp.link = front->link;
- delete front;
- front = temp.link;
- return temp.elem;
- }
- // 判断队列是否为空
- template <typename CustomType>
- bool JChainQueue<CustomType>::IsEmpty( void )
- {
- if ( front == rear )
- return true;
- else return false;
- }
- // 取出队列头元素
- template <typename CustomType>
- CustomType JChainQueue<CustomType>::GetFront( void )
- {
- return front->elem;
- }
- #endif
测试一下,我使用了两个实例,一个是用最简单的结构“char”型来对其实例化,另外一个稍微复杂些,使用了一个结构体来验证。经过一步又一步的调试,我终于得出了比较稳定的链式队列结构,或者说我的队列健壮性(鲁棒性)还是不错的。
下面是我的测试:
- #include<iostream>
- #include"JChainQueue.h"
- using namespace std;
- // 测试②
- struct stCustom
- {
- int a;
- char b[20];
- unsigned long c;
- };
- int main( int argc, char** argv)
- {
- /*--------------------测试①------------------------
- JChainQueue<char> temporary;
- char a = 'A', b = 'B', c = 'C';
- temporary.EnterQueue( a );
- temporary.EnterQueue( b );
- cout<<"出队列的是:"<<temporary.DeleteQueue();
- cout<<"现在队列头是:"<<temporary.GetFront();
- ----------------------------------------------------*/
- // 测试②
- JChainQueue<stCustom> temporary2;
- stCustom obj[3] =
- {
- 1, "这个好!", 31415926,
- 2, "这个很好!", 27145082,
- 3, "这个非常好!", 4529392,
- };
- temporary2.EnterQueue( obj[0] );
- temporary2.EnterQueue( obj[1] );
- cout<<"出队列的是:"<<temporary2.DeleteQueue().a<<"号/n";
- cout<<"现在队列头是:"<<temporary2.GetFront().a<<"号,它的内容是:"<<temporary2.GetFront().b<<'/n';
- return 0;
- }
测试的结果如下图:
①
②
有了队列,我们就可以对我们的二叉树进行遍历的操作了,太好了,我要升级了!下一次我就会介绍我制作的二叉树。这个二叉树可是我三天来的成果啊!!!