队列的链式实现

本文介绍了如何使用链式存储来实现队列,包括队头和队尾的概念,以及链式队列的数据插入和删除操作。同时提供了Queue.h和main.cpp的实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、链式队列

队列不仅可以用顺序存储,也可以向单链表一样,用链式存储,只不过队列链式存储需要头指针(front)和尾指针(rear),分别指向队头和队尾,数据只能在对头一端删除, 在队尾一端插入。

图示:

二、实现代码

Queue.h

#pragma once
#define ElemType int
//链式队列
typedef struct
{
	ElemType data;//数据域
	struct Node* next;//指针域
}Node;
typedef struct 
{
	struct Node* front;//队头指针
	struct Node* rear;//队尾指针
}Queue,*PQueue;

Node* BuyNode(ElemType val);
void InitQueue(PQueue pq);//初始化队列
bool Push(PQueue pq, ElemType val);//入队
bool GetTop(PQueue pq, ElemType *rtval);//获取队头的值,但不删除
bool Pop(PQueue pq);//出队
bool IsEmpty(PQueue pq);//判断对列为空
void Display(PQueue pq);//显示对列元素
Queue.cpp

#include <iostream>
#include "Queue.h"
using namespace std;

void InitQueue(PQueue pq)
{
	pq->front = NULL;
	pq->rear = NULL;
}
Node *BuyNode(ElemType val)
{
	Node *p = (Node *)malloc(sizeof(Node));
	if (NULL == p) return NULL;
	p->data = val;
	p->next = NULL;
	return p;
}
bool Push(PQueue pq, ElemType val)
{
	Node *p = BuyNode(val);
	if (pq->rear != NULL)
	{
		pq->rear->next = p;
		pq->rear = p;
	}
	else
	{
		pq->front = p;
		pq->rear = p;
	}
	return true;
}
bool GetTop(PQueue pq, ElemType *rtval)
{
	if (IsEmpty(pq))
	{
		return false;
	}
	*rtval = pq->front->data;
	return true;
}
bool Pop(PQueue pq)
{
	if (IsEmpty(pq))
	{
		return false;
	}
	Node *p = pq->front;
	pq->front = p->next;
	free(p);
	if (pq->front == NULL)
	{
		pq->rear = NULL;
	}
	return true;
}
bool IsEmpty(PQueue pq)
{
	return pq->front == NULL;
}

void Display(PQueue pq)
{
	Node *p = pq->front;
	while (p != NULL)
	{
		cout << p->data << " ";
	}
	cout << endl;
}

main.cpp

#include <iostream>
#include "Queue.h"
using namespace std;

int main()
{
	Queue List;
	InitQueue(&List);
	for (int i = 0; i < 10; ++i)
	{
		Push(&List,i);
	}
	Display(&List);
	Pop(&List);
	Display(&List);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值