队列的链式存储与相关操作

本文介绍了一种使用链表实现队列的存储方法,并详细解释了如何进行初始化、入队和出队等基本操作。文章通过示例代码展示了具体的实现过程,特别强调了在进行出队操作时对尾指针的正确处理。

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

一、队列的链式存储与相关操作

注意

  1. 存储结构(带头结点)

    如图:q.frontq.frontq.front指向的单元为头结点,而队头的实际位置为q.front−>nextq.front->nextq.front>next.
  2. q.popq.popq.pop操作时,在释放队头指针前,应该先判断所poppoppop的元素是否是最后一个,是最后一个的话需要先将尾指针指向头指针,不然会造成尾指针的丢失。

代码

#include<iostream>
#include<cstring>
#include<cstdlib>
#define OK 1
#define ERROR -1
using namespace std;
typedef int ElemType;
typedef int Status;
typedef struct node{
	ElemType data;
	struct node *next;
}Qnode;
typedef struct {
	Qnode *front;  // 队头指针
	Qnode *rear;  // 队尾指针
}LinkQueue;
Status InitQueue(LinkQueue *q)
{
	q->front = q->rear = (Qnode *)malloc(sizeof(Qnode));
	if (!q->front)
		return ERROR;
	return OK;
}
bool QueueEmpty(LinkQueue *q)
{
	return q->front == q->rear;
}
Status Push(LinkQueue *q, ElemType e)
{
	Qnode * temp = (Qnode *)malloc(sizeof(Qnode));
	if (!temp)
		return ERROR;
	temp->data = e;
	temp->next = NULL;
	q->rear->next = temp;
	q->rear = temp;
	return OK;
}
Status Pop(LinkQueue *q, ElemType *e)
{
	Qnode *temp;
	if (QueueEmpty(q))
		return ERROR;
	temp = q->front->next;  //带头结点,q->front->next 才是值
	*e = temp->data;
	q->front->next = temp->next;
	if (q->rear == temp)
		q->rear = q->front;
	free(temp);
	return OK;
}
int main()
{
	LinkQueue *q;
	InitQueue(q);
	for (int i = 1;i <= 9;i++)
		Push(q, i);
	for (int i = 1;i <= 9;i++) { //顺序输出
		ElemType temp;
		Pop(q, &temp);
		cout << temp << ' ';
	}
	cout << endl;
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值