关闭

C++实现队列之链式存储结构

标签: C++数据结构vs队列链式存储
180人阅读 评论(0) 收藏 举报
分类:
#include <iostream>
#include <string>

using namespace std;

template<typename T>
struct LinkNode{
	T data;
	LinkNode<T> *next;
};

template<typename T>
class LinkQueue{
public:
	LinkQueue();
	LinkQueue(T a[], int n);
	~LinkQueue(){ Clear(); cout << "hehe" << endl; };
	void InputQue(T x);
	void OutQue();
	void Gethead();
	void Empty();
	void Clear();
	void Print();
private:
	LinkNode<T> *front, *rear;
};

template<typename T>
LinkQueue<T>::LinkQueue()         //构造函数初始化一个空链队
{
	front = new LinkNode <T>;
	front->next = NULL; 
	rear = front;
}

template<typename T>
LinkQueue<T>::LinkQueue(T a[], int n)
{
	front = new LinkNode <T>;           //分配一个头结点
	rear = front;
	front->next = NULL;
	for (int i = 0; i < n; ++i)
	{
		LinkNode<T> *newNode = new LinkNode <T>;
		newNode->data = a[i];
		newNode->next = rear->next;                 //队尾入队操作
		rear->next = newNode;
		rear = newNode;
	}
}

template<typename T>
void LinkQueue<T>::InputQue(T x)          //入队
{
	LinkNode<T> *newNode = new LinkNode < T > ;
	newNode->data = x;
	newNode->next = rear->next;
	rear->next = newNode;
	rear = newNode;
}

template<typename T>
void LinkQueue<T>::OutQue()              //出队,返回队列首元素
{
	LinkNode<T> *p = front;
	if (p != rear)
	{
		p = p->next;
		T x = p->data;
		front->next = p->next;
		delete p;
		cout<< x<<endl;
	}
}

template<typename T>
void LinkQueue<T>::Gethead()            //取队首元素
{
	LinkNode<T> *p = front;
	if (p != rear)
	{
		p = p->next;
		T x = p->data;
		cout << x << endl;
	}
}

template<typename T>
void LinkQueue<T>::Print()             //队头到队尾 遍历队列
{
	LinkNode<T> *p = front;
	while (p->next != rear)
	{
		p = p->next;
		cout << p->data << " ";
	}
	cout << rear->data << endl;
}

template<typename T>
void LinkQueue<T>::Empty()                //判断空否?
{
	if (front == rear)
		cout << "队列为空!" << endl;
	else
		cout << "队列非空!" << endl;
}

template<typename T>
void LinkQueue <T>::Clear()        //清空链队
{
	while (front != rear)
	{
		LinkNode<T> *p = front;
		p = p->next;
		front->next = p->next;
		if (p->next == NULL)
			rear = front;         //这一步必不可少
		delete p;
	}
	delete front;
	cout << "已清空" << endl;
}


int _tmain(int argc, _TCHAR* argv[])
{
	int a[] = {1,2,3,4,5,6};
	LinkQueue<int> A(a, 6);
	A.Print();
	A.InputQue(7);
	A.Print();
	A.OutQue();
	A.Print();
	A.Gethead();
	A.Empty();
	//A.Clear();

	return 0;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4217次
    • 积分:166
    • 等级:
    • 排名:千里之外
    • 原创:13篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条
    文章存档
    最新评论