C语言-队列

前言

emmm…

代码

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
110
111
#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>

//循环队列
typedef struct Queue{
int *pBase;
int front;
int rear;
}Queue;

void initQueue(Queue* pq)
{
pq->front = -1;
pq->rear = 0;
pq->pBase = malloc(sizeof(int)*6);//限定队列长度为6
}

bool isfull(Queue pq)
{
if((pq.rear)%6 == pq.front)
return true;
else
return false;
}

bool isempty(Queue pq)
{
if(pq.front == -1)
return true;
return false;
}

//入队
void insert(Queue* pq, int val)
{
printf("insert:%d,%d\n",val ,pq->rear);
if(isempty(*pq))
{
pq->pBase[pq->rear] = val;
pq->rear = (pq->rear+1)%6;
pq->front ++;
return;
}
if(isfull(*pq))
{
printf("%d,%d\n",pq->front,pq->rear );
printf("insert isfull\n");
return;
}
pq->pBase[pq->rear] = val;
pq->rear = (pq->rear+1)%6;
}

//遍历
void traverse(Queue *pq)
{
if(isempty(*pq))
{
printf("traverse empty\n");
return;
}
int i = pq->front;
while(i%6!= pq->rear || i<6)
{
printf("%d,",pq->pBase[i]);
i++;
}
printf("\n");
}

//出队
void out_queue(Queue* pq)
{
if (isempty(*pq))
{
printf("out_queue,error\n");
return;
}
pq->front = (pq->front + 1)%6;
if(pq->front == pq->rear)
{
pq->front = -1;
pq->rear = 0;
}
}

int main()
{
Queue Q;
initQueue(&Q);
insert(&Q,1);
insert(&Q,2);
insert(&Q,3);
insert(&Q,4);
insert(&Q,5);
insert(&Q,6);
insert(&Q,6);

traverse(&Q);
out_queue(&Q);

out_queue(&Q);
out_queue(&Q);
out_queue(&Q);
out_queue(&Q);
out_queue(&Q);
out_queue(&Q);
traverse(&Q);
return 0;
}