3.6链队列

.队列:只允许在一端进行插入,在另一端进行删除的线性表。

链队列:使用链表实现的队列;具有队头指针和队尾指针,指示队列元素所在的位置。

链队列特性:

  • 只能队尾插入元素、在队头删除元素。
  • 先进先出(First In First Out)的线性表,先进入的元素出队,后进入的元素才能出队。

优点:

  • 相比普通的队列,元素出队时无需移动大量元素,只需移动头指针。
  • 可动态分配空间,不需要预先分配大量存储空间。
  • 适合处理用户排队等待的情况。

缺点:

  • 需要为表中的逻辑关系增加额外的存储空间。

时间复杂度

  • 读取时的时间复杂度为O(1)。
  • 插入、删除时的时间复杂度为O(1)。

帆哥的代码:

#include <stdio.h>
#include <malloc.h>

/**
 * 链队列的节点.
 */
typedef struct LinkNode{
	int data;
	LinkNode* next;
}*LinkNodePtr;

/**
 * 链队列.
 */
typedef struct LinkQueue{
	LinkNodePtr front;
	LinkNodePtr rear;
}*LinkQueuePtr;

/**
 * Construct an empty queue.
 */
LinkQueuePtr initQueue(){
	LinkQueuePtr resultPtr = (LinkQueuePtr)malloc(sizeof(struct LinkQueue));
	//The header, the data is not useful.
	LinkNodePtr headerPtr = (LinkNodePtr)malloc(sizeof(struct LinkNodePtr));
	headerPtr->next = NULL;
	
	resultPtr->front = headerPtr;
	resultPtr->rear = headerPtr;
	return resultPtr;
}//Of initQueue

/**
 * Output the queue.
 */
void outputLinkQueue(LinkQueuePtr paraQueuePtr){
	LinkNodePtr tempPtr = paraQueuePtr->front->next;
	while (tempPtr != NULL) {
		printf("%d ", tempPtr->data);
		tempPtr = tempPtr->next;
	}//Of while
	printf("\r\n");
}//Of outputLinkQueue

/**
 * Enqueue.
 */
void enqueue(LinkQueuePtr paraQueuePtr, int paraElement) {
	//Step 1. Create a new node
	LinkNodePtr tempNodePtr = (LinkNodePtr)malloc(sizeof(struct LinkNode));
	tempNodePtr->data = paraElement;
	tempNodePtr->next = NULL;
	
	//Step 2. Link to the existing rear
	paraQueuePtr->rear->next = tempNodePtr;
	
	//Step 3. 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值