// Implementation file for Stack demo

// see stack.h for function headers and documentation

// Marc Chee (cs1511@cse.unsw.edu.au), November 2020

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

#include "stack.h"


// Struct governing the whole stack
// The head is considered the top of the stack
struct stackInternals {
    struct stackNode *head;
    int size;
};

struct stackNode {
    int data;
    struct stackNode *next;
};

// Create an empty stack
Stack stackCreate(void) {
    // Stack can be used in place of struct stackInternals *
    Stack newStack = malloc(sizeof(struct stackInternals));
    newStack->head = NULL;
    newStack->size = 0;    
    return newStack;
}

// Add an item to the top of the stack
void stackPush(Stack s, int item) {
    // create a new stack node and attach it to the current stack
    struct stackNode *newNode = malloc(sizeof(struct stackNode));
    newNode->data = item;
    newNode->next = s->head;
    
    // aim the stack's head at this new node
    s->head = newNode;
    s->size++;
}

// Remove the top item from the stack and return its data
int stackPop(Stack s) {
    // check whether the head exists
    if (s->head == NULL) {
        // there are no elements in this stack, end program
        printf("Attempted to pop an element from an empty stack.\n");
        exit(1);
    }
    
    // if we reach this point, there is at least 1 element in the stack
    int popData = s->head->data;
    struct stackNode *remNode = s->head;
    s->head = remNode->next;
    free(remNode);
    s->size--;
    
    return popData;
}

// returns the current size of the stack
int stackSize(Stack s) {
    return s->size;
}


Resource created Tuesday 10 November 2020, 01:17:43 PM.

file: stack.c


Back to top

COMP1511 20T3 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G