-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathll_queue.c
106 lines (65 loc) · 1.69 KB
/
ll_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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdio.h>
#include <stdlib.h>
typedef struct listNode {
char datum;
struct listNode *next;
} ListNode;
typedef struct queue {
ListNode *head;
ListNode *tail;
} Queue;
void push (Queue **nodePtr2, char datum);
void purge (Queue *list);
int pop (Queue **list);
void print (ListNode **list);
char peek (ListNode **list);
int main (void) {
printf("\nThis is a Linked List implementation of a queue.\n\n");
printf("HEAD <----- TAIL\n\n");
Queue *list = malloc(sizeof(Queue));
push(&list, 'a'); // adds to top of stack (end of list)
push(&list, 'b');
push(&list, 'c');
push(&list, 'd');
print(&(list->head));
printf("Peeked: %c\n\n", peek(&(list->head)));
pop(&list);
print(&(list->head));
purge(list);
return 0;
}
void push (Queue **nodePtr2, char datum) { // pass in first node of list
// create new node
ListNode *newNode = malloc(sizeof(ListNode));
if (!newNode) return;
newNode -> datum = datum;
newNode -> next = NULL;
Queue *cur = *nodePtr2;
if (!cur->head) {
cur->head = newNode;
cur->tail = cur->head;
return;
} else {
cur->tail->next = newNode;
cur->tail = cur->tail->next;
}
}
void purge (Queue *list) {
free(list);
}
int pop (Queue **list) {
Queue *cur = *list;
ListNode *tmp = cur->head;
cur->head = cur->head->next;
free(tmp);
return 0;
}
void print (ListNode **list) {
printf("|");
for (ListNode *node = *list; node != NULL; node = node -> next)
printf(" %c |", node -> datum);
printf("\n\n");
}
char peek (ListNode **list) {
return (*list)->datum;
}