链式队列的实现

本文详细介绍了使用链表实现队列的数据结构,并提供了队列的多种操作函数实现及测试案例,展示了队列的基本应用。

本程序是队列的实现,利用链表实现了对队列的一些操作


头文件:定义了队列类以及一些结点结构

//Filename:queue.h
//Writed by CaoLichen
//head file

#pragma once										//防止头文件被重复引用

//template<class T>									//模板
typedef struct Node{								//定义队列数据结点类型
	int data;
	struct Node *next;
}QNode;

typedef struct {									//队列类型定义
	QNode *front;									//队头
	QNode *rear;									//队尾
}LiQueue;			


//template <typename Type>							//定义类模板
class Queue{
public:
	Queue();										//构造函数,初始化
	void InQueue(int data);							//进队列
	int OutQueue();									//出队列,返回值为1,表示出队列成功,0表示出队列失败
	int IsEmpty();									//判断队列是否为空,返回0为空,返回1不为空
	int Length();									//队列长度,返回队列长度
	void Print();									//打印队列

private:
	LiQueue *q;
};

一下程序是类中各种函数的定义:

//Filename:queue.cpp
//Writend by CaoLichen

#include "queue.h"
#include<cstdlib>
#include<iostream>

Queue::Queue(){													//初始化
	q = (LiQueue *)malloc(sizeof(LiQueue));
	q->front = q->rear = NULL;
}

void Queue::InQueue(int data){									//进队列
	QNode *tmp;
	tmp = (QNode*)malloc(sizeof(QNode));
	tmp->data = data;
	tmp->next = NULL;

	if(q->rear == NULL){										//若队列为空,则新结点
		q->rear = q->front = tmp;
	}

	else{
		q->rear->next = tmp;									//将新结点链到队尾,并将rear指针指向他
		q->rear = tmp;
	}
	
}

int Queue::OutQueue(){											//出队列
	if(q->rear == NULL){
		return 0;												//队列为空,出对失败,返回0
	}

	else{
		QNode *tmp;												//将front指针后移,并销毁原对头
		tmp = q->front;
		if(q->front == q->rear){								//队列中只有一个结点
			q->front = q->rear = NULL;
		}

		else{
			q->front = tmp->next;
		}
		
		free(tmp);
		return 1;
	}
}

int Queue::Length(){											//求队列长度
	int count = 0;												//计算器
	QNode *tmp;
	tmp = q->front;												//定位到队列头

	while(tmp != NULL){
		tmp = tmp->next;
		count ++;
	}

	return count;
}

int Queue::IsEmpty(){											//判断队列是否为空
	if(q->rear == NULL){
		return 0;												//rear指针为空,则队列为空,返回0
	}

	else{
		return 1;
	}
}

void Queue::Print(){											//打印队列
	if(q->rear == NULL){
		std::cout<<"队列为空!\n";
	}
	else{
		QNode *tmp;
		tmp = q->front;
		while(tmp != NULL){
			std::cout<<tmp->data<<" ";
			tmp = tmp->next;
		}

		std::cout<<"\n";
	}
}

以下程序是一些测试,比较粗糙:

//Filename:main.cpp
//Writed by CaoLichen
//test file

#include "queue.h"
#include<iostream>

int main(){
	Queue A;
	for(int i = 0; i < 20; i ++){
		A.InQueue(i);
		std::cout<<"队列长度:"<<A.Length()<<"\n";
		A.Print();
	}

	for(int i = 0; i < 20; i ++){
		A.OutQueue();
		std::cout<<"队列长度:"<<A.Length()<<"\n";
		A.Print();
	}

	for(int i = 0; i < 20; i ++){
		A.InQueue(i);
		std::cout<<"队列长度:"<<A.Length()<<"\n";
		A.Print();
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值