加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

【数据结构】 队列的实现

发布时间:2020-12-15 06:33:27 所属栏目:安全 来源:网络整理
导读:学习数据结构基础,如有错误,请指正 /***数据结构:队列的模拟,创建、销毁、进队列、出队列打印输出字符,模拟先进现出特性***/#ifndef __LINKQUEUE_H__#define __LINKQUEUE_H__typedef char ElemType;struct LinkNode{ElemType data;LinkNode *next;};cla

学习数据结构基础,如有错误,请指正


/***
数据结构:队列的模拟,创建、销毁、进队列、出队列
打印输出字符,模拟先进现出特性
***/

#ifndef __LINKQUEUE_H__
#define __LINKQUEUE_H__
typedef char ElemType;

struct LinkNode{
	ElemType data;
	LinkNode *next;
};

class LinkQueue{
public:
	LinkQueue();
	~LinkQueue();

	void enterQueue(ElemType e);
	ElemType exitQueue();
	void print();
private:
	LinkNode *front;
	LinkNode *rear;

	void initLinkQueue();
	void destroyLinkQueue();

};

#endif // __LINKQUEUE_H__


#include "LinkQueue.h"
#include <iostream>
using std::cout;
using std::endl;

LinkQueue::LinkQueue()
{
	this->initLinkQueue();
}
LinkQueue::~LinkQueue()
{
	this->destroyLinkQueue();
}

void LinkQueue::initLinkQueue()
{
	this->front = new LinkNode();
	if (!this->front)
	{
		exit(0);
	}

	this->rear = this->front;
	this->front->next = NULL;
}

void LinkQueue::destroyLinkQueue()
{

#if 1
	while (this->front != this->rear)
	{
		LinkNode *q = this->front->next;
		this->front->next = q->next;

		if (q == this->rear)
		{
			this->rear = this->front;
			delete q;
		}
	}
#else
	while(this->front){
		this->rear = this->front->next;
		delete this->front;
		this->front= this->rear;
	}
#endif

	this->front = NULL;
	this->rear = NULL;
}

void LinkQueue::enterQueue(ElemType e)
{
	LinkNode *q = new LinkNode;
	q->data =e;
	q->next = NULL;
	this->rear->next = q;
	this->rear= q;
}

ElemType LinkQueue::exitQueue()
{
	if (this->front == this->rear)
	{
		exit(0);
		cout<<"queue is empty."<<endl;
	}

	LinkNode *q = this->front->next;
	int e = q->data;

	this->front->next = q->next;
	if (q = this->rear)
	{
		this->front = this->rear;
	}

	return e;
}

void LinkQueue::print()
{
	if (this->front == this->rear) 
		return;

	LinkNode* q = this->front->next;
	cout<<"print queue:"<<endl;
	while(q){
		cout<<q->data;
		q = q->next;
	}
}


int main()
{
	LinkQueue *queue = new LinkQueue();

	cout<<"enter queue:"<<endl;
	for (int i=0;i <10;++i)
	{
		char aChar = rand()%20+40;
		queue->enterQueue(aChar);
		cout<<aChar;
	}
	cout<<endl;

	queue->print();

	getchar();

	return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读