// Implementation file for a Stack using an Array
// Part of a demo for Abstract Data Types
// Marc Chee April 2019

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

#include "stack.h"

#define MAX_STACK_SIZE 1024

// Struct representing the stack using an array
struct stackInternals {
    int stackData[MAX_STACK_SIZE];
    int top;
};

// create a new stack
stack stackCreate() {
    stack s = malloc(sizeof struct stackInternals);
    if (s == NULL) {
        printf("Cannot allocate memory for a stack.\n");
        exit(1);
    }
    s->top = 0;
    return s;
}

// Add an element to the top of the stack
void stackPush(stack s, int item) {
    // check to see if we've used up all our memory
    if(s->top == MAX_STACK_SIZE) {
        printf("Maximum stack size reached, cannot push.\n");
        exit(1);
    }
    s->stackData[s->top] = item;
    s->top++;
}

// Remove an element from the top of the stack
int stackPop(stack s) {
    // check to see if the stack is empty
    if(s->top <= 0) {
        printf("Stack is empty, cannot pop.\n");
        exit(1);
    }
    s->top--;
    return s->stackData[s->top];
}

Resource created Tuesday 23 April 2019, 02:02:50 AM, last modified Wednesday 24 April 2019, 03:46:56 PM.

file: stack.c


Back to top

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