数据结构系列7 - 队 - 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* Author: TyrantLucifer
* Function: Link Queue
* Time: 2020-07-14
*/

#include <stdio.h>
#include <stdlib.h>

#define SUCCESS 1
#define FAIL 0

/*define Queue Node struct*/
typedef struct QNode{
int data;
struct QNode* next;
}QNode;

/*define Queue head Node struct*/
typedef struct LiQueue{
struct QNode* front;
struct QNode* rear;
}LiQueue;

/*init queue*/
LiQueue* initQueue(){
LiQueue* L = (LiQueue*)malloc(sizeof(LiQueue));
L->front = NULL;
L->rear = NULL;
}

/*
* print queue
* L: the point of queue
*/
int printQueue(LiQueue* L){
QNode* node = L->front;
while(node){
printf("%d\t", node->data);
node = node->next;
}
printf("\n");
}

/*
* judge queue is or not empty
* L: the point of queue
*/
int isEmpty(LiQueue* L){
if(L->front == NULL || L->rear == NULL){
return SUCCESS;
}
else{
return FAIL;
}
}

/*
* enqueue
* data: the value you want to enqueue
* S: the pointer of queue
*/
int enQueue(int data, LiQueue* L){
QNode* node = (QNode*)malloc(sizeof(QNode));
node->data = data;
node->next = NULL;
if(L->rear == NULL){
L->rear = L->front = node;
node->next = NULL;
}
else{
L->rear->next = node;
L->rear = node;
}
}

/*
* dequeue
* S: the pointer of queue
*/
int deQueue(LiQueue* L){
if(isEmpty(L)){
return FAIL;
}
else{
QNode* node = L->front;
int data = node->data;
if(L->front == L->rear){
L->front = L->rear = NULL;
}
else{
L->front = node->next;
}
free(node);
return data;
}
}

/*main function*/
int main(){
LiQueue* L = initQueue();
enQueue(1, L);
enQueue(2, L);
enQueue(3, L);
printQueue(L);
deQueue(L);
printQueue(L);
return 0;
}