【数据结构复习04】队列的链式存储实现以及基本操作

队列的链式存储实现以及基本操作

队列的链式存储类型描述

typedef struct Node{		//链式队列节点
	int data;
	struct Node *next;
}LinkNode;
typedef struct Queue{		//链式队列
	LinkNode *front,*rear;	//队头与队尾指针
}LiQueue;

注意事项

  1. 总体上和单链表的操作相同,只不过是存取受限。值得注意的是定义“链式队列”结构体时,要注意和单链表的定义不一样。“链式队列”结构体里面已经包含了指针,所以在起别名时不用再加*号,否则会变成指针的指针
  2. 注意带头节点的描述与不带头节点的描述,两种描述的判空条件不同。本文采取的是带头节点的方式。

源代码如下

#include<stdio.h>
#include<stdlib.h>

typedef struct Node{
	int data;
	struct Node *next;
}LinkNode;
typedef struct Queue{
	LinkNode *front,*rear;
}LiQueue;

//初始化 
bool InitQueue(LiQueue &queue){
	if(queue.front=queue.rear=(Node *)malloc(sizeof(Node)))	//带头节点 
		return false;
	
	queue.rear->next=NULL;									//初始栈为空 
	return true;
}

//判空 
bool EmptyQueue(LiQueue queue){
	if(queue.front->next==NULL)
		return true;
	return false;
}
//入队列 
bool EnQueue(LiQueue &queue,int e){
	LinkNode *p=(LinkNode *)malloc(sizeof(LinkNode));
	if(p==NULL)
		return false;
	p->data=e;
	p->next=NULL;
	queue.rear->next=p;
	queue.rear=p;
	return true;
}
//获取队头 
bool GetHead(LiQueue queue,int &head){
	if(EmptyQueue(queue))
	{
		printf("队列为空,无队头!\n");
		return false;
	}
		
	head=queue.front->next->data;
	return true;
}

//出队列 
bool DeQueue(LiQueue &queue,int &de){
	if(EmptyQueue(queue)){
		return false;
	}
	de=queue.front->next->data;
	LinkNode *p;
	p=queue.front->next;
	if(p==queue.rear)
		queue.rear=queue.front;
	queue.front->next=p->next;
	 
	free(p);
	return true;
} 

//得到队列长度
int GetLen(LiQueue queue)
{
	if(EmptyQueue(queue))
		return 0;
	int len=0;
	while(queue.front->next!=NULL){
		len++;
		queue.front=queue.front->next;
	}
	return len;
		
}

//输出队列 
bool PrintQueue(LiQueue queue){
	if(EmptyQueue(queue))
		return false;
		
	LinkNode *p;
	p=queue.front->next;
	printf("队列为:");
	while(p!=NULL){
		printf("\t%d\n",p->data);
		p=p->next;
	}
	return true;
} 

int main()
{
	
	LiQueue queue;
	int head,de;
	
	InitQueue(queue);
	
	EnQueue(queue,1);
	
	EnQueue(queue,2);
	
	EnQueue(queue,3);
	
	EnQueue(queue,4);
	
	EnQueue(queue,5);
	
	EnQueue(queue,6);
	
	PrintQueue(queue);
	
	printf("Len:%d\n",GetLen(queue));
	
	if(GetHead(queue,head)){
		printf("head:%d\n",head);		
	}
	
	printf("head:%d\n",head);
	
	if(DeQueue(queue,de))	
		printf("de:%d\n",de);
	else
		printf("栈为空!\n"); 
	
	if(DeQueue(queue,de))	
		printf("de:%d\n",de);
	else
		printf("栈为空!\n"); 
	
	if(DeQueue(queue,de))	
		printf("de:%d\n",de);
	else
		printf("栈为空!\n"); 
		
	EnQueue(queue,2);
	
	if(GetHead(queue,head)){
		printf("head:%d\n",head);		
	}
	
	PrintQueue(queue);
	system("pause");
	return 0;
 } 

效果展示
在这里插入图片描述
The End…

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值