队列的概念
两种队列的实现
1.静态队列
数据结构:
typedef struct ls//数组实现的静态队列
{
int buffer[MAX_SIZE];
int head = 0;//头指针
int tear = -1;//尾部指针
int count = 0;//元素个数
}Queue;count用于计数,这样不在需要计算队列中含有元素的个数了
进队列操作:
bool EnQueue(Queue* Qu,int date)//静态队列入
{
if (Qu->count > MAX_SIZE)return 0;//数据满了返回0
if (++Qu->tear > MAX_SIZE - 1)Qu->tear = 0;//尾部溢出则指向头部
Qu->buffer[Qu->tear] = date;
Qu->count++;
return 1;
}
出队列操作:
bool DeQueue(Queue* Qu, int *date)//静态队列出
{
if (Qu->count == 0)return 0;//空队列返回0
if (++Qu->head > MAX_SIZE - 1)Qu->head = 0;
Qu->count--;
return 1;
}count=0时则表示该队列为空,返回0
2.链队列
数据结构
typedef struct item
{
int data = 0;
item*next = NULL;
}LinkNode,*NodePtr;
typedef struct elem//需要队列头和队列尾部
{
NodePtr head = NULL;
NodePtr tear = NULL;
int lenth = 0;//队列长度
}LinkQueue;LinkNode为链表节点进队列操作
bool EnQueue(LinkQueue* Qu,int date)//入队列
{
NodePtr e = (NodePtr)malloc(sizeof(LinkNode));
e->data = date;
e->next = NULL;
if (Qu->tear == NULL)//如果队列为空 也可以判断lenth
{
Qu->head = e;
Qu->tear = e;
Qu->lenth = 1;
}
else
{
Qu->tear->next = e;
Qu->tear = e;
Qu->lenth++;//长度自加一位
}
return 1;
}操作方法入上所述
出队列操作
bool DeQueue(LinkQueue*Qu, int*date)//出队列
{
if (Qu->lenth == 0)return 0;//空队列
NodePtr temp = Qu->head;
*date = temp->data;
if (Qu->head == Qu->tear)//也可以判断lenth为0
{
Qu->head = NULL;
Qu->tear = NULL;
}
else
{
Qu->head = Qu->head->next;
}
Qu->lenth--;
free(temp);
return 1;
}
2754



被折叠的 条评论
为什么被折叠?



