链队列实例C++代码实现

list_queue.h

#pragma once
#define Queue_Datatype int
#define Init_QueueData 99
#include<iostream>

class Queue_Node {
public:
	Queue_Node() {
		data = Init_QueueData;
		next = NULL;
	}

	Queue_Node(Queue_Datatype x) : data(x), next(NULL) {

	}

	Queue_Datatype data;
	Queue_Node *next;
};

class MyQueue
{
public:
	MyQueue();
	MyQueue(int size);
	~MyQueue();

	void Init_Queue();		//	初始化队列
	void Destory_Queue();	//	摧毁队列
	void Clear_Queue();		//	清空队列

	bool Queue_Empty();		//	是否为空队列
	int Queue_Size();		//  队列长度

	int Queue_Head();		//	获取队头数据
	bool Queue_Push(Queue_Datatype x);		//	入队
	bool Queue_Pop();		//	出队

	void Print_Queue();		//  遍历队列

private:
	Queue_Node* front;				//	队头
	Queue_Node* rear;				//	队尾
};


list_queue.cpp

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

MyQueue::MyQueue()
{
	Init_Queue();
}

MyQueue::MyQueue(int size)
{
	Init_Queue();
	for (int i = 0; i < size; i++) {
		Queue_Datatype temp;
		std::cin >> temp;
		Queue_Push(temp);
	}
}

MyQueue::~MyQueue()
{
	Clear_Queue();
	Destory_Queue();
}


void MyQueue::Init_Queue()
{
	Queue_Node *temp = new(std::nothrow) Queue_Node;
	if (!temp)
		std::exit(1);
	front = temp;
	rear = temp;
}

void MyQueue::Destory_Queue()
{
	delete(front);
}

void MyQueue::Clear_Queue()
{
	if (Queue_Empty())    
		return;

	Queue_Node *cur = front->next;
	Queue_Node *next = cur->next;

	while (cur != rear) 
	{    
		delete(cur);
		cur = next;
		next = next->next;
	}

	delete(rear);
	rear = front;
}

bool MyQueue::Queue_Empty()
{
	return (front == rear) ? true : false;
}

int MyQueue::Queue_Size()
{
	int num = 0;
	Queue_Node *temp = front;
	while (temp!=rear)
	{
		num++;
		temp = temp->next;
	}
	return num;
}

int MyQueue::Queue_Head()
{
	if (Queue_Empty())
		std::cout << "队列为空" << std::endl;
		return false;
	Queue_Datatype value = front->next->data;
	return value;
}

bool MyQueue::Queue_Push(Queue_Datatype x)
{
	Queue_Node* temp = new(std::nothrow) Queue_Node(x);

	if (!temp)
		std::exit(1);

	rear->next = temp;
	rear = temp;

	return true;
}

bool MyQueue::Queue_Pop()
{
	if (Queue_Empty())
		std::cout << "队列为空" << std::endl;
	return false;

	if (Queue_Size() == 1) {
		delete(front->next);
		front->next = NULL;
		rear = front;
	}
	else {
		Queue_Node* node = front->next;
		front->next = node->next;
		delete(node);
	}

	return true;
}

void MyQueue::Print_Queue()
{
	Queue_Node* cur = front->next;

	while (cur != NULL) 
	{
		std::cout << cur->data << std::endl;
		cur = cur->next;
	}
}

test.cpp

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

int main()
{
	std::cout << "请输入元素: " << std::endl;
	MyQueue a(3);
	std::cout << "队列长度: " << a.Queue_Size() << std::endl;
	a.Print_Queue();

	a.Queue_Push(10);
	std::cout << "插入元素后的队列遍历: " << std::endl;
	a.Print_Queue();

	std::cout << "队头元素: " << a.Queue_Head() << std::endl;
	system("pause");
	return 0;
}

在这里插入图片描述

posted @ 2021-02-03 20:56  code_witness  阅读(58)  评论(0编辑  收藏  举报