Last active
April 25, 2022 18:47
-
-
Save boki1/44e7441273d88c04c1512d7abd708836 to your computer and use it in GitHub Desktop.
Dynamic queue implementation - School HW
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
struct queue_node | |
{ | |
char x; | |
struct queue_node *next; | |
}; | |
struct queue | |
{ | |
struct queue_node *head; | |
struct queue_node *tail; | |
}; | |
typedef struct queue q_t; | |
typedef struct queue_node node_t; | |
int enqueue(q_t *queue, char val) | |
{ | |
node_t *new = calloc(1, sizeof(node_t)); | |
if (!new) | |
return 1; | |
new->x = val; | |
new->next = 0; | |
if (!queue->tail) | |
queue->tail = new; | |
else | |
queue->head->next = new; | |
queue->head = new; | |
return 0; | |
} | |
int dequeue(char *out, q_t *queue) | |
{ | |
if (!queue->tail) | |
return 1; | |
*out = queue->tail->x; | |
node_t *res = queue->tail; | |
queue->tail = queue->tail->next; | |
free(res); | |
return 0; | |
} | |
void print_queue(q_t *queue) | |
{ | |
node_t *current = queue->tail; | |
printf("The queue is:\n"); | |
while (current) | |
{ | |
printf("%c --> ", current->x); | |
current = current->next; | |
} | |
printf("NULL\n\n"); | |
} | |
void init(q_t *queue) | |
{ | |
queue->head = queue->tail = 0; | |
} | |
int main() | |
{ | |
q_t *queue = malloc(sizeof(q_t)); | |
init(queue); | |
char item; | |
int choice; | |
int res; | |
printf("%s\n%s\n%s\n%s\n", | |
"Enter your choice: ", | |
" 1 to add an item to the queue", | |
" 2 to remove an item from the queue", | |
" 3 to end" | |
); | |
while (choice != 3) | |
{ | |
printf("? "); | |
scanf("%d", &choice); | |
switch (choice) | |
{ | |
case 1: | |
printf("Enter a character: "); | |
scanf("\n%c", &item); | |
enqueue(queue, item); | |
break; | |
case 2: | |
res = dequeue(&item, queue); | |
if (!res) | |
printf("\'%c\' has beed dequeued.\n", item); | |
break; | |
} | |
print_queue(queue); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment