前面三次的链接如下:
数据结构01----单链表
数据结构02----双链表
数据结构03----栈
本篇来说一下数据结构中的队列。
五、队列
队列是是一种先进先出(FIFO)的线性表,只允许在一端进行插入(入队)操作,在另一端进行删除(出队)操作。
队列中,允许入队操作的一端叫做队尾,允许出队操作的一端叫做队头。
和之前的栈一样,C语言实现分两种讲解:链队列和顺序队列。
1.链队列
在链表的基础上,按照先进先出的原则操作数据。
C语言编程思路:
①结点定义;
②链表初始化; 定义头结点,赋值给头指针、尾指针
③入队: 尾插
出队: 删除首元结点,释放堆空间
如下图:
上图对应的C程序如下:
#include <stdio.h>
#include <stdlib.h>
//1、定义链表节点
typedef struct Link
{
int data;
struct Link *next;
}link;
//2、初始化
link *init_link(void)
{
link *head=(link *)malloc(sizeof(link));
head->next=NULL;
return head;
}
//3、入队,相当于尾插
void enqueue(link **head,int elem)
{
link *node=(link *)malloc(sizeof(link));
node->data=elem;
link *temp=*head;
while(temp->next!=NULL)
{
temp=temp->next;
}
node->next=NULL;
temp->next=node;
}
//4、出队:相当于删除首元节点
link *dequeue(link *head)
{
if (head->next==NULL)
{
printf("队列已空!\n");
}
else
{
link *temp=head->next;
printf("%d\n",temp->data);
head->next=temp->next;
free(temp);
}
return head;
}
int main(int argc, char const *argv[])
{
link *head=init_link();
enqueue(&head,10);
enqueue(&head,20);
enqueue(&head,30);
enqueue(&head,40);
head=dequeue(head);
head=dequeue(head);
head=dequeue(head);
head=dequeue(head);
head=dequeue(head);
return 0;
}
运行结果如下:
2.顺序队列
把申请的空间想象成环状空间。
C语言编程思路:
①定义数组,存放数组大小的宏,头尾指针并赋初值;
②入队; 先判断是否已满。
出队; 先判断是否为空。
将判断是否已满和为空两种情况区分的方法:
牺牲掉一个存储空间。即尾指针的下一个位置与头指针相遇说明满了。请仔细理解并消化下面图片和例程。
如下图:
对应编程实例如下:
#include <stdio.h>
void enqueue(int *a,int *tail,int elem)
{
if (*tail==10)
{
printf("队列已满!\n");
}
else
{
a[(*tail)++]=elem;
}
}
void dequeue(int *a,int *head,int *tail)
{
if (*head==*tail)
{
printf("队列为空!\n");
}
else
{
printf("%d\n",a[(*head)++]);
}
}
int main(int argc, char const *argv[])
{
int a[10];
int head,tail;
head=tail=0;
enqueue(a,&tail,10);
enqueue(a,&tail,20);
enqueue(a,&tail,30);
enqueue(a,&tail,40);
enqueue(a,&tail,50);
dequeue(a,&head,&tail);
dequeue(a,&head,&tail);
dequeue(a,&head,&tail);
dequeue(a,&head,&tail);
dequeue(a,&head,&tail);
dequeue(a,&head,&tail);
enqueue(a,&tail,10);
enqueue(a,&tail,20);
enqueue(a,&tail,30);
enqueue(a,&tail,40);
enqueue(a,&tail,50);
dequeue(a,&head,&tail);
dequeue(a,&head,&tail);
dequeue(a,&head,&tail);
dequeue(a,&head,&tail);
dequeue(a,&head,&tail);
dequeue(a,&head,&tail);
enqueue(a,&tail,10);
dequeue(a,&head,&tail);
return 0;
}
运行结果: