// 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;
    int size;
};

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;
    newQueue->size = 0;
    return newQueue;
}

// free an entire queue
void queueFree(Queue q) {
    /*while (q->head != NULL) {
        struct queueNode *remNode = q->head;
        q->head = q->head->next;
        free(remNode);
    }*/
    while(q->head != NULL) {
        queueRemove(q);
    }
    free(q);
}

// 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;
    }
    q->size++;
}

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;
        }
        q->size--;
    }
    
    return data;
}

int queueSize(Queue q) {
    /*struct queueNode *iterator = q->head;
    int counter = 0;
    while (iterator != NULL) {
        counter++;
        iterator = iterator->next;
    }
    return counter;*/
    return q->size;
}




Resource created Monday 05 August 2019, 02:15:03 PM.

file: queueLec.c


Back to top

COMP1511 19T2 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G