// Linked List Implementation of a Queue
// Marc Chee (marc.chee@unsw.edu.au) July 2019
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
struct queueInternals {
struct queueNode *head;
struct queueNode *tail;
};
struct queueNode {
int data;
struct queueNode *next;
};
// Create a new queue, that is currently empty
Queue queueCreate() {
Queue newQueue = malloc(sizeof(struct queueInternals));
if (newQueue == NULL) {
printf("Could not create queue, memory allocation failed.\n");
exit(1);
}
newQueue->head = NULL;
newQueue->tail = NULL;
return newQueue;
}
// Add a queueNode to the end of the list (just after tail)
void queueAdd(Queue q, int item) {
struct queueNode *newNode = malloc(sizeof (struct queueNode));
if (newNode == NULL) {
printf("Could not create queue node, memory allocation failed.\n");
exit(1);
}
newNode->data = item;
newNode->next = NULL;
// Add newNode to queue
if (q->tail == NULL) {
// q is empty
q->head = newNode;
q->tail = newNode;
} else {
// q has at least one node
q->tail->next = newNode;
q->tail = newNode;
}
}
int queueRemove(Queue q) {
int data;
if (q->head == NULL) {
printf("Attempt to remove from an empty queue.\n");
exit(1);
} else {
data = q->head->data;
struct queueNode *remNode = q->head;
q->head = q->head->next;
free(remNode);
if (q->head == NULL) {
// the list is now empty
q->tail = NULL;
}
}
return data;
}
Resource created Tuesday 30 July 2019, 08:34:11 PM.
file: queueLec.c