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