数据结构课后题源码
2016-05-24 15:58
232 查看
题目描述:若使用链表来表示队列。试基于此结构给出队列的插入函数(EnQueue)和删除函数(DeQueue)算法。
此题比较简单,但是得熟练运用c++的指针,也容易出错误,还有得注意的是重载操作符函数的模板类形式!下面是源代码:
其中得注意的是friend ostrream & operator<<<>(ostream os, ListQueue<T> & l)函数,这里很容易出错,记得使用一个临时指针先保存l.front的指向的值,然后再指回来!
这个<>是模板类编程的形式,但它不需要加T,所以得注意一下!上述代码是博主自己码的,各位看官,不喜勿喷!
此题比较简单,但是得熟练运用c++的指针,也容易出错误,还有得注意的是重载操作符函数的模板类形式!下面是源代码:
#ifndef LISTQUEUE_H_ #define LISTQUEUE_H_ #include <iostream> using namespace std; template<class T> struct ListQueueNode { T data; ListQueueNode<T> * link; }; template<class T> class ListQueue{ private: ListQueueNode<T> * front, *rear; public: ListQueue(); ~ListQueue(); void EnQueue(const T & x); bool DeQueue(T & x); friend ostream & operator<<<>(ostream & os, ListQueue<T> & l); }; template<class T> ListQueue<T>::ListQueue() { front = rear = NULL; } template<class T> ListQueue<T>::~ListQueue() { ListQueueNode<T> * temp; while (front->link != NULL) //删除至队列的最后一个节点 { temp = front; front = front->link; delete temp; } } template<class T> void ListQueue<T>::EnQueue(const T & x) { if (front == NULL)//如果对列为空则该节点成为队列的第一个节点 { ListQueueNode<T> * newNode = new ListQueueNode < T >; front = rear = newNode; newNode->data = x; rear->link = NULL; } else//队列不为空 { ListQueueNode<T> * newNode = new ListQueueNode < T >; newNode->data = x; rear->link = newNode; rear = newNode; rear->link = NULL; } } template<class T> bool ListQueue<T>::DeQueue(T & x) { if (front == NULL) { cout << "队列为空,无法进行出队列操作!" << endl; return false; } else { ListQueueNode<T> * temp; temp = front; front = front->link; x = temp->data; delete temp; } } template<class T> ostream & operator<<<>(ostream & os, ListQueue<T> & l) //友元函数,重载操作符<< { ListQueueNode<T> *temp = l.front; while (l.front != NULL) //当队列不为空时继续输出 { os << l.front->data << " "; //进行调试后,我知道是这里除了问题, l.front = l.front->link; } os << endl; l.front = temp; return os; } #endif
// ex3-25.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "ListQueue.h" int _tmain(int argc, _TCHAR* argv[]) { ListQueue<int> a; int value; for (int i = 0; i < 5; i++) //初始化,为简单起见,测试程序默认输入5个节点,当然可以随意决定输入节点数,因为这是链表表示的队列,所以不会产生溢出 { cout << "请输入插入的第" << i + 1 << "个节点的值: "; cin >> value; a.EnQueue(value); } cout << a; //确认输入的5个节点值 int temp; a.DeQueue(temp); //进行出队列测试 cout << a; //检查出队列结果 system("pause"); return 0; }
其中得注意的是friend ostrream & operator<<<>(ostream os, ListQueue<T> & l)函数,这里很容易出错,记得使用一个临时指针先保存l.front的指向的值,然后再指回来!
这个<>是模板类编程的形式,但它不需要加T,所以得注意一下!上述代码是博主自己码的,各位看官,不喜勿喷!
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- C#数据结构之顺序表(SeqList)实例详解
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(七):数据结构详解
- Lua教程(二):C++和Lua相互传递数据示例
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构之队列(Quene)实例详解
- C#数据结构揭秘一
- C#数据结构之单链表(LinkList)实例详解
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题