-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.c
More file actions
134 lines (114 loc) · 2.25 KB
/
Queue.c
File metadata and controls
134 lines (114 loc) · 2.25 KB
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
https://powcoder.com
代写代考加微信 powcoder
Assignment Project Exam Help
Add WeChat powcoder
// Implementation of the Queue ADT using a linked list
// !!! DO NOT MODIFY THIS FILE !!!
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "Queue.h"
struct node {
Item item;
struct node *next;
};
struct queue {
struct node *head;
struct node *tail;
int size;
};
static struct node *newNode(Item it);
/**
* Creates a new empty queue
*/
Queue QueueNew(void) {
Queue q = malloc(sizeof(*q));
if (q == NULL) {
fprintf(stderr, "couldn't allocate Queue\n");
exit(EXIT_FAILURE);
}
q->head = NULL;
q->tail = NULL;
q->size = 0;
return q;
}
/**
* Frees all resources associated with the given queue
*/
void QueueFree(Queue q) {
struct node *curr = q->head;
while (curr != NULL) {
struct node *temp = curr;
curr = curr->next;
free(temp);
}
free(q);
}
/**
* Adds an item to the end of the queue
*/
void QueueEnqueue(Queue q, Item it) {
struct node *n = newNode(it);
if (q->size == 0) {
q->head = n;
} else {
q->tail->next = n;
}
q->tail = n;
q->size++;
}
static struct node *newNode(Item it) {
struct node *n = malloc(sizeof(*n));
if (n == NULL) {
fprintf(stderr, "error: out of memory\n");
exit(EXIT_FAILURE);
}
n->item = it;
n->next = NULL;
return n;
}
/**
* Removes an item from the front of the queue and returns it
* Assumes that the queue is not empty
*/
Item QueueDequeue(Queue q) {
assert(q->size > 0);
struct node *newHead = q->head->next;
Item it = q->head->item;
free(q->head);
q->head = newHead;
if (newHead == NULL) {
q->tail = NULL;
}
q->size--;
return it;
}
/**
* Gets the item at the front of the queue without removing it
* Assumes that the queue is not empty
*/
Item QueueFront(Queue q) {
assert(q->size > 0);
return q->head->item;
}
/**
* Gets the size of the given queue
*/
int QueueSize(Queue q) {
return q->size;
}
/**
* Returns true if the queue is empty, and false otherwise
*/
bool QueueIsEmpty(Queue q) {
return q->size == 0;
}
/**
* Prints the queue to the given file with items space-separated
*/
void QueueDump(Queue q, FILE *fp) {
for (struct node *curr = q->head; curr != NULL; curr = curr->next) {
fprintf(fp, "%d ", curr->item);
}
fprintf(fp, "\n");
}