-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.c
More file actions
106 lines (91 loc) · 1.75 KB
/
queue.c
File metadata and controls
106 lines (91 loc) · 1.75 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
#include<stdio.h>
#include<stdlib.h>
struct Node
{
double element;
struct Node * next;
};
struct Queue
{
struct Node *head;
struct Node *tail;
int size;
};
struct Queue *newQueue(void);
void enqueue(struct Queue *, double);
void dequeue(struct Queue *);
void toString(struct Queue *);
void testQueue(struct Queue *);
void freeQueue(struct Queue *);
struct Queue* newQueue()
{
struct Queue *q = (struct Queue*)malloc(sizeof(struct Queue));
q->head = NULL;
q->tail = NULL;
q->size = 0;
return q;
}
void freeQueue(struct Queue *q)
{
struct Node *current = q->head;
struct Node * temp = current;
while(current != NULL)
{
temp = current->next;
current = temp;
free(temp);
}
free(q);
}
void enqueue(struct Queue *q, double newElement)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->element = newElement;
newNode->next = NULL;
struct Node *temp = newNode;
temp->next = NULL;
if(q->size == 0)
q->head = newNode;
else
q->tail->next = newNode;
q->tail = newNode;
q->size++;
free(temp);
}
void dequeue(struct Queue *q)
{
if(q->size == 0)
return;
struct Node *temp = q->head;
temp->next = NULL;
q->head = q->head->next;
free(temp);
q->size--;
if(q->size == 0)
q->tail = NULL;
}
void toString(struct Queue *q)
{
struct Node *current = (struct Node*)malloc(sizeof(struct Node));
for (current = q->head; current != NULL; current = current->next)
{
struct Node *temp = current;
printf(" %f", current->element);
free(temp);
}
printf("\n");
free(current);
}
void testQueue(struct Queue *q)
{
enqueue(q, 2.);
toString(q); //2
enqueue(q, 4.);
toString(q); //2, 4
enqueue(q, 6.);
toString(q);//2, 4, 6
dequeue(q);
toString(q);//4, 6
enqueue(q, 8.);
toString(q);// 4, 6, 8
}