数据结构之队列

1 . 队列的基本概念
    只允许在一端进行插入数据操作(队尾),在另一端进行删除数据操作(队头)的特殊线性表。队列具有先进先出的特性。
2 . 队列存储结构
顺序队列:
队头指针不动----要大量搬移元素(出队列时所有元素向前移动)
队头指针移动----存在假溢出
循环队列
循环队列如何解决队列空或者满?(三种方法)
a 少用一个存储空间(队列空:front=rear.队列满:(rear+1)%size==front.)
b设置一个标记位 :入队列 flag置为1,出队列flag置为0.当(flag==0)&&(front==rear)队列为空,当(flag==1)&&(front==rear)队列为满。
c 设置一个计数器,记录队列中元素的个数,当count==0时队列为空,count==size时队列为满。 
链式队列---用链表作为队列的底层数据结构
实现链式队列的以下操作:
typedef int DataType;
typedef struct Node
{
DataType _data;
struct Node* _pNext;
}Node, *PNode;

typedef struct Queue
{
PNode _pHead;
PNode _pTail;
}Queue;

// 队列的初始化
void QueueInit(Queue* q);

// 入队列
void QueuePush(Queue* q, DataType data);

// 出队列
void QueuePop(Queue* q);

// 取队头元素
DataType QueueFront(Queue* q);

// 取队尾元素
DataType QueueBack(Queue* q);

// 获取队列中元素的个数
int QueueSize(Queue* q);

// 检测队列是否为空
int QueueEmpty(Queue* q);
下边是实现代码:

#include<malloc.h>
#include<stdio.h>
#include<Windows.h>
#define NULL 0
typedef int DataType;
typedef struct Node
{
	DataType _data;
	struct Node* _pNext;
}Node, *PNode;

typedef struct Queue 
{
	PNode _pHead;
	PNode _pTail;
}Queue;

// 队列的初始化
void QueueInit(Queue* q){
	q->_pHead = q->_pTail=NULL;
}
PNode buynode(DataType data){
	PNode temp;
	temp = (PNode)malloc(sizeof(Node));
	if (NULL == temp){
		return;
	}
	temp->_data = data;
	return temp;
}
// 入队列
void QueuePush(Queue* q, DataType data){
	if (q->_pHead == NULL){
		q->_pHead = buynode(data);
		q->_pTail = q->_pHead;
		q->_pHead->_pNext = NULL;
	}
	else{
		q->_pTail = buynode(data);
		q->_pHead->_pNext = q->_pTail;
		q->_pTail->_pNext = NULL;
	}
}

// 出队列
void QueuePop(Queue* q){
	if (NULL == q)
	{
		return;
	}
	q->_pHead = q->_pHead->_pNext;
}

// 取队头元素
DataType QueueFront(Queue* q){
	if (NULL == q)
	{
		return NULL;
	}
	return q->_pHead->_data;
}

// 取队尾元素
DataType QueueBack(Queue* q){
	if (NULL == q){
		return NULL;
	}
	return q->_pTail->_data;
}

// 获取队列中元素的个数
int QueueSize(Queue* q){
	if (NULL == q){
		return 0;
	}
	int count = 1;
	PNode temp ;
	temp = q->_pHead;
	while (temp!=q->_pTail){
		count++;
		temp = temp->_pNext;
	}
	return count;
}

// 检测队列是否为空
int QueueEmpty(Queue* q){//空返回1,不空返回0.
	if (q->_pHead == q->_pTail==NULL){
		return 1;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值