您的位置:首页 > 理论基础 > 数据结构算法

数据结构课后题源码

2016-05-24 15:58 232 查看
题目描述:若使用链表来表示队列。试基于此结构给出队列的插入函数(EnQueue)和删除函数(DeQueue)算法。

此题比较简单,但是得熟练运用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,所以得注意一下!上述代码是博主自己码的,各位看官,不喜勿喷!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息