// Implementation file for a Queue
// Part of a demo for Abstract Data Types
// Marc Chee 18/4/2019

#include <stdlib.h>
#include <stdio.h>

#include "queue.h"

// Struct representing the entire queue
struct queueInternals {
    struct queueNode *head;
    struct queueNode *tail;
    int size;
};

// a single node/element of the queue
struct queueNode {
    struct queueNode *next;
    int data;
};

static int checkMemory(void *pointer, char message[]);

// Create an empty queue and return the queue type that refers to it
queue queueCreate() {
    struct queueInternals *newQueue = malloc(sizeof(struct queueInternals));
    if(checkMemory(newQueue, "queue")) {
        newQueue->head = NULL;
        newQueue->tail = NULL;
        newQueue->size = 0;
    }
    return newQueue;
}

// Destroy and Free the entire queue
void queueFree(queue q) {
    while (q->head != NULL) {
        struct queueNode *current = q->head;
        q->head = q->head->next;
        free(current);
    }
    free(q);
}

// Add an element after the current tail of the queue
// It will also set the tail to the new last element
void queueAdd(queue q, int item) {
    struct queueNode *newNode = malloc(sizeof(struct queueNode));
    if(checkMemory(newNode, "node")) {
        newNode->data = item;
        newNode->next = NULL;
    }
    if(q->tail == NULL) {
        // list is empty
        q->head = newNode;
        q->tail = newNode;
    } else {
        q->tail->next = newNode;
        q->tail = newNode;
    }
    q->size++;
}

// Remove the head of the queue, returning its integer value
// Move the head pointer to the new head
int queueRemove(queue q) {
    if(q->head == NULL) {
        printf("Can't remove an object from an empty queue");
        exit(1);
    }
    
    // keep track of original head node
    int nodeItem = q->head->data;
    struct queueNode *oldHead = q->head;
    
    // Move head to new head of the queue
    q->head = q->head->next;
    
    // free the memory for the node that's no longer in use
    free(oldHead);
    
    q->size--;
    
    return nodeItem;
}

// Return the number of items in the queue
int queueSize(queue q) {
    
    return q->size;
    
    /*
    struct queueNode *iterator = q->head;
    int counter = 0;
    while(iterator != NULL) {
        counter++;
        iterator = iterator->next;
    }
    return counter;
    */
}

// helper function for checking memory
static int checkMemory(void *pointer, char message[]) {
    if(pointer == NULL) {
        printf("Cannot allocate memory for %s", message);
        exit(1);
    }
    return 1;
}




Resource created Tuesday 23 April 2019, 02:00:20 AM, last modified Wednesday 24 April 2019, 03:39:48 PM.

file: queue.c


Back to top

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