【数据结构】 队列的实现

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


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

#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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值