Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
queue/queue.c
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
74 lines (63 sloc)
1.34 KB
This file contains 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 <assert.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include "queue.h" | |
Queue* create_queue() { | |
Queue* queue = malloc(sizeof(Queue)); | |
queue->size = 0; | |
queue->head = NULL; | |
queue->tail = NULL; | |
return queue; | |
} | |
int front(Queue* queue) { | |
assert(!is_empty(queue)); | |
return queue->head->data; | |
} | |
int back(Queue* queue) { | |
assert(!is_empty(queue)); | |
return queue->tail->data; | |
} | |
void enqueue(Queue* queue, int data) { | |
QueueNode* node = malloc(sizeof(QueueNode)); | |
node->data = data; | |
node->next = NULL; | |
if (is_empty(queue)) { | |
queue->head = queue->tail = node; | |
} else { | |
queue->tail->next = node; | |
queue->tail = node; | |
} | |
queue->size++; | |
} | |
int dequeue(Queue* queue) { | |
assert(!is_empty(queue)); | |
int data = front(queue); | |
QueueNode* dequeued_node = queue->head; | |
queue->head = queue->head->next; | |
free(dequeued_node); | |
queue->size--; | |
return data; | |
} | |
void destroy_queue(Queue* queue) { | |
QueueNode* current = queue->head; | |
while (current) { | |
QueueNode* next = current->next; | |
free(current); | |
current = next; | |
} | |
free(queue); | |
} | |
void print_queue(Queue* queue) { | |
QueueNode* current = queue->head; | |
while (current) { | |
printf("%d ", current->data); | |
current = current->next; | |
} | |
printf("\n"); | |
} | |
size_t size(Queue* queue) { | |
return queue->size; | |
} | |
int is_empty(Queue* queue) { | |
return queue->size == 0; | |
} |