-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathQueue.c
88 lines (75 loc) · 1.67 KB
/
Queue.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
// Queue.c ... implementation of Queue ADT
// Written by John Shepherd, March 2013
// Taken from course material - never changed but it was needed for Item.h.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "Queue.h"
#include "Item.h"
typedef struct QueueNode {
Item value;
struct QueueNode *next;
} QueueNode;
typedef struct QueueRep {
QueueNode *head; // ptr to first node
QueueNode *tail; // ptr to last node
} QueueRep;
// create new empty Queue
Queue newQueue (void)
{
QueueRep *new = malloc (sizeof *new);
*new = (QueueRep){ .head = NULL, .tail = NULL };
return new;
}
// free memory used by Queue
void dropQueue (Queue Q)
{
assert (Q != NULL);
for (QueueNode *curr = Q->head, *next; curr != NULL; curr = next) {
next = curr->next;
free (curr);
}
free (Q);
}
// display as 3 > 5 > 4 > ...
void showQueue (Queue Q)
{
assert (Q != NULL);
for (QueueNode *curr = Q->head; curr != NULL; curr = curr->next) {
ItemShow (curr->value);
if (curr->next != NULL)
printf (">");
}
printf ("\n");
}
// add item at end of Queue
void QueueJoin (Queue Q, Item it)
{
assert (Q != NULL);
QueueNode *new = malloc (sizeof *new);
assert (new != NULL);
*new = (QueueNode){ .value = ItemCopy (it), .next = NULL };
if (Q->head == NULL)
Q->head = new;
if (Q->tail != NULL)
Q->tail->next = new;
Q->tail = new;
}
// remove item from front of Queue
Item QueueLeave (Queue Q)
{
assert (Q != NULL);
assert (Q->head != NULL);
Item it = ItemCopy (Q->head->value);
QueueNode *old = Q->head;
Q->head = old->next;
if (Q->head == NULL)
Q->tail = NULL;
free (old);
return it;
}
// check for no items
int QueueIsEmpty (Queue Q)
{
return (Q->head == NULL);
}