队列的链表方式实现

目录

 

队列的基础知识

初始化一个队列节点

入队

出队

链表实现代码

程序运行结果


  • 队列的基础知识

  1. 队列遵循先进先出,即FIFO(first in first out)。例如:我们经常见到的排队买票、排队买饭等等;
  2. 队列的两个基本操作:

入队 :将一个数据放到队列尾部;

出队 :从队列的头部取出一个元素。

  • 初始化一个队列节点

inline qu* Init_Queue(qu* q, int data)  //初始化一个队列节点
{
	q->data = data;
	q->next = NULL;

	return q;
}
  • 入队

qu* Insert_Queue(qu* q, int data, int q_length)
{
	qu* head = q;
	qu* cut = q;
	int  i = 0;
	if (q_length <= 0 || NULL == q)  //参数合法性判断
	{
		cout << "Error queue length or queue is't init." << endl;
		return NULL;
	}
	for (i = 0; i < q_length; i++)  //依次插入数据
	{
		qu* newq = (qu*)malloc(sizeof(qu));

		if (head->next == NULL)  //只有一个头节点
		{
			head->next = newq;
			cut = newq;
			Init_Queue(newq, data + i);
		}
		else                     //已经又出头节点之外其他节点
		{
			cut->next = newq;
			Init_Queue(newq, data + i);
			cut = newq;

		}

	}

	return q;

}
  • 出队

void Out_Queue(qu* q, int q_length)
{
	int  i = 0;
	if (NULL == q)
		return;
	qu* head = q;

	cout << "出队:"<<endl;
	cout << endl;
	q = head->next;  //跳过头节点
	for(i = 1; i< q_length +1; ++i)
	{           
		if (q->next != NULL)
		{
			
			cout << q->data << "  ";
		}
		else
			cout << q->data << "  ";

		q = q->next;
	}

}
  • 链表队列的实现代码

#include <iostream>  
#include <string>
using namespace std;

typedef struct queue
{
	int            data;
	struct queue*   next;
}qu;

inline qu* Init_Queue(qu* q, int data);            //初始化一个队列的节点
qu* Insert_Queue(qu* q, int data, int q_length);   //入队
void Out_Queue(qu* q, int q_length);                             //出队

int main()
{
	qu* q1;
	q1 = (qu *)malloc(sizeof(qu));
	qu* q2 = Insert_Queue(Init_Queue(q1, -1), 96, 21);
	Out_Queue(q2, 21);
	return 0;
}

inline qu* Init_Queue(qu* q, int data)
{
	q->data = data;
	q->next = NULL;

	return q;
}
qu* Insert_Queue(qu* q, int data, int q_length)
{
	qu* head = q;
	qu* cut = q;
	int  i = 0;
	if (q_length <= 0 || NULL == q)
	{
		cout << "Error queue length or queue is't init." << endl;
		return NULL;
	}
	cout << "入队:" << endl;

	for (i = 0; i < q_length; i++)
	{
		qu* newq = (qu*)malloc(sizeof(qu));

		if (head->next == NULL)
		{
			head->next = newq;
			cut = newq;
			Init_Queue(newq, data + i);
			cout << newq->data << "  ";
		}
		else
		{
			cut->next = newq;
			Init_Queue(newq, data + i);
			cout << newq->data << "  ";
			cut = newq;

		}

	}

	return q;

}

void Out_Queue(qu* q, int q_length)
{
	int  i = 0;
	if (NULL == q)
		return;
	qu* head = q;

	cout << "出队:"<<endl;

	q = head->next;  //跳过头节点
	for(i = 1; i< q_length +1; ++i)
	{           
		if (q->next != NULL)
		{
			
			cout << q->data << "  ";
		}
		else
			cout << q->data << "  ";

		q = q->next;
	}


}
  • 程序运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XiaoCheng'Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值