4. ©数据结构-队列(顺序&&链式)
这一节我当初花了好大功夫理解,最后还是靠一张示意图获救, 果然图画是最美丽的语言,这里只展示教材上顺序存储实现的循环队列,和链式存储的对列
顺序存储的循环队列
我们需要两个指针:一个是 front头指针,指向队头;一个是 rear尾指针,指向队尾。入队front后移,出队rear后移
我们为什么需要循环存储的队列呢,
下面这种最基础的实现方式,随着出队入队的进行,最后会出现一种假溢出的问题,
故我们采用循环队列,并少用一个元素空间,下图就展示了该方法下队列满的情况
计算队满条件: (尾部+1)%数组长度==头部
队列中元素个数 (尾巴-头部+数组长度)%数组长度
链式存储
注意,队列的头front必须指向链表的头节点,尾rear必须指向链表的尾节点(原因在注释里)
循环顺序存储代码
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#define MAXSIZE 100
typedef int Position;
typedef struct QNode * PtrToQNode;
typedef int ElementType;
struct QNode
{
ElementType *Data;
Position Front, Rear;
int MaxSize;
};
typedef PtrToQNode Queue;
/*循环队列的创建,插入,删除*/
Queue CreatQueue(int MaxSize)
{
Queue Q ;
Q = (Queue)malloc(sizeof(struct QNode));
Q->Data = (ElementType*)malloc(MAXSIZE*sizeof(ElementType));
Q ->Front = Q->Rear = 0;
return Q;
}
bool IsFull(Queue Q)
{
return((Q->Rear+1)%Q->MaxSize == Q->Front);
}
bool AddQ(Queue Q, ElementType X)
{
if(IsFull(Q)){
printf("队列满");
return false;
}
else{
Q->Rear = (Q->Rear+1)%Q->MaxSize;
Q->Data[Q->Rear]=X;
return true;
}
}
bool IsEmpty(Queue Q)
{
return(Q->Rear==Q->Front);
}
ElementType DeleteQ(Queue Q)
{
if(IsEmpty(Q))
{
printf("队列空");
return ERROR;
}
else {
/*我们不需要真的做什么删除操作,因为我们对队列各种操作都是基于两个指针来的*/
/*只要把front后移,之后做入队判断时就已经把那里默认为空了,有入队需求那里直接覆盖就ok了*/
Q->Front = (Q->Front+1)%Q->MaxSize;
return Q->Data[Q->Front];
}
}
链式
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#define MAXSIZE 100
typedef int Position;
typedef struct Node * PtrToNode;
typedef int ElementType;
/*指针一定要初始化*/
/*队列中节点节点本身的信息*/
/*Next是负责把节点串在一起*/
struct Node
{
ElementType Data;
PtrToNode Next;
};
/*下面这个结构来代表队列*/
typedef PtrToNode Position;
typedef struct QNode *PtrToQNode;
/*队列的头front必须指向链表的头结点,队列的尾必须指向链表的尾节点*/
/*理由如下*/
/*首先插入,无论是在链表头还是链表尾都没问题*/
/*删除,链表头没问题,在链表尾删除,就需要知道尾部前一个元素,我们现有的这个结构不能知道尾部前一个元素*/
/*除非你用指针从头再遍历一下,这样就得不偿失了,所以做删除操作的front不能再表尾,只能在表头*/
struct QNode{
Position Front,Rear;
int MaxSize;
};
typedef PtrToQNode Queue;
//创建一个队列
Queue CreatQueue()
{
Queue Q;
Q = (Queue)malloc(sizeof(struct QNode));
Q ->Front = NULL;
Q ->Rear = NULL:
return Q;
}
//判断是否为空
bool IsEmpty(Queue Q)
{
return(Q->Front == NULL);
}
//入队
/*实际上就是在链表的尾部插入节点*/
void AddQ(Queue Q, ElementType X)
{
Position node;
node = (Position)malloc(sizeof(struct Node));
node ->Data = X;
node ->Next = NULL;
if(IsEmpty(Q)) //如果队列为空
{
Q->Rear = node;
Q->Front = node;
}
else
{
Q->Rear->Next = node; //节点入队
Q->Rear = node; //rear后移,使它总指向链表尾节点
}
}
//出队
/*在头部删除节点*/
ElementType DeleteQ(Queue Q)
{
Position FrontCell;
ElementType FrontElem; //记录那个被删掉的值,返回给命令框让我们看到
if(IsEmpty(Q))
{
printf("队列空");
return ERROR;
}
else
{
FrontCell = Q->Front;
if(Q->Front == Q->Rear) //此时队列只有一个元素,需要将rear和front都指针移回null
Q->Front = Q->Rear = NULL;
else //否则只需要将front后移一位
Q->Front = Q->Front->Next;
FrontElem=FrontCell->Data;
free(FrontCell); //释放被删除节点空间
return FrontElem;
}
}