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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <stdio.h>
#include <stdlib.h>

// because the C language does not has the type of boolean ,so , we use replace of which int,example 1 and 0 replace of the "true" and "false"
#define true 1
#define false 0

// alias name by int
typedef int elementType;

// design the queue data stuct
typedef struct queue
{
elementType *content;
elementType front;
elementType rear;
elementType maxSize;
}QUEUE,*PQUEUE;

// define the func
PQUEUE createQueue(); // create one queue , return the queue
int isFull(PQUEUE queue); // is Full
int isEmpty(PQUEUE queue); // is Empty
int enQueue(PQUEUE queue,int data); // EnQueue , include isFull
int deQueue(PQUEUE queue); // DeQueue, include isEmpty
//void loop_print(PQUEUE queue); // Loop Print the queue;

void main()
{
// define the queue
PQUEUE queue = NULL;

printf(" Please Input the queue of length :");
int length;
scanf("%d",&length);

// invoke func
queue = createQueue(length);

while(true)
{
printf(" Please Input which your want to enQueue the data:");
int data ;
scanf("%d",&data);
if(data == 0)
{
break;
}
// invoke func
enQueue(queue,data);
}

char *result = (char *)malloc(sizeof(char));
while(true)
{
printf("deQueue :");
int data = deQueue(queue);
printf("data : %d\n",data);

printf(" Go on ? [yes|no]\n");
scanf("%s",result);
if(strcmp(result,"yes") != 0)
{
break;
}
}
}


PQUEUE createQueue(int maxSize)
{
PQUEUE p = (PQUEUE)malloc(sizeof(PQUEUE));
if(p == NULL)
{
printf("malloc apply fail");
exit(-1);
}

if(maxSize < 1)
{
printf("the queue size does not < 1");
exit(-1);
}
maxSize++;

// when the front end rear equals ,the queue is empty
p->front = p->rear = 0;
p->maxSize = maxSize;
p->content = (elementType *)malloc(sizeof(elementType)); // init Mem

// return the queue of point;
return p;
}

int enQueue(PQUEUE queue,int data)
{
if(isFull(queue)){
printf("The queue is fullest,data : %d\n",data);
exit(-1);
}
queue->content[queue->rear] = data;
queue->rear = (queue->rear+1)%queue->maxSize;
}

int isFull(PQUEUE queue)
{
if((((queue->rear)+1)%queue->maxSize == queue->front))
{
return true;
}

return false;
}

int isEmpty(PQUEUE queue)
{
if(queue->rear == queue->front && queue->maxSize > 0)
{
return true;
}

return false;
}

int deQueue(PQUEUE queue)
{
if(isEmpty(queue))
{
printf("队列为空");
exit(-1);
}

int data = queue->content[queue->front];
queue->front = (queue->front+1)%queue->maxSize;

return data;
}