本程序是队列的实现,利用链表实现了对队列的一些操作
头文件:定义了队列类以及一些结点结构
//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;
}
本文详细介绍了使用链表实现队列的数据结构,并提供了队列的多种操作函数实现及测试案例,展示了队列的基本应用。
5万+

被折叠的 条评论
为什么被折叠?



