数据结构-队列

数据结构:队列

队列作为一种数据结构,只能从一端添加元素,只能从另一端取出元素。

队列的应用可以在播放器上的播放列表,数据流对象,异步的数据传输结构(文件IO,管道通讯,套接字等)上体现,当然最直观的的就是排队了。

队列和栈的最大区别就是:栈是先进后出,队列是先进先出,根据这个区别能很快的根据栈的操作写出队列

队列的创建和初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define ERROR_CODE -108
#define EMPTY_CODE -109

typedef struct linklist
{
int number;
struct linklist *next;
}LINKLIST;

LINKLIST *init_list()
{
LINKLIST *head,*end;
head = (LINKLIST*)malloc(sizeof(LINKLIST));
end = head;
end->next = NULL;
return head;
}
C

和栈一样,队列也采用单链表实现

判断队列为空

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool is_empty(LINKLIST *list)
{
if (list == NULL )
{
printf("stack is not exit!\n");
exit(EMPTY_CODE);
}
if (list->next == NULL)
{
return true;
}


return false;
}
C

如果只有一个头节点则队列为空

入队

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int push(LINKLIST *list,int number)
{
LINKLIST *node;
if (list == NULL)
{
return ERROR_CODE;
}

node = (LINKLIST*)malloc(sizeof(LINKLIST));
node->number = number;
node->next = list->next;
list->next = node;

return 0;
}
C

头插法,每次入队都插入到队列最前面

出队

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int pop(LINKLIST *list)
{
int number;

if (list == NULL)
{
return ERROR_CODE;
}

if (is_empty(list))
{
return EMPTY_CODE;
}

while (list->next->next != NULL)
{
list = list->next;
}

number = list->next->number;
free(list->next);
list->next = NULL;

return number;
}
C

出队时,从队尾出队,保证先进先出
如果入队采用尾插法,出队则需要从头部出队

删除队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int del(LINKLIST **list)
{
if (*list == NULL)
{
return ERROR_CODE;
}
while ((*list)->next != NULL)
{
pop(*list);
}

free(*list);
*list = NULL;

}
C

将所有节点出队,最后删除头结点


数据结构-队列
https://carl-5535.github.io/2020/11/27/数据结构/数据结构-队列/
作者
Carl Chen
发布于
2020年11月27日
许可协议