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

// 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;
    }
    return newQueue;
}

// 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;
    }
    if(q->tail == NULL) {
        // list is empty
        q->head = newNode;
        q->tail = newNode;
    } else {
        q->tail->next = newNode;
        q->tail = newNode;
    }
    
}

// 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);
    
    return nodeItem;
}

// 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 Thursday 18 April 2019, 12:32:36 AM, last modified Monday 22 April 2019, 04:24:10 PM.

file: queueLec.c


Back to top

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