// Implementation of a stack based on stack.h
// Each element stored is an integer

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

#include "stack.h"

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

#define MAX_STACK 1024

struct stackInternals {
    int stackItems[MAX_STACK];
    int top;
};

// Create a new stackInternals and return a pointer to it
Stack stackCreate(void) {
    struct stackInternals *newStack = malloc(sizeof(struct stackInternals));
    newStack->top = 0;
    return newStack;
}

// Free memory used for the stack
void stackFree(Stack s) {
    free(s);
}

// Add an item to the top of the stack 
// Uses top as the index for the new item
void stackPush(Stack s, int item) {
    if (s->top >= MAX_STACK) {
        // stack has used up the whole array
        printf("Stack has run out of space, cannot push another item.\n");
        exit(1);
    } else {
        s->stackItems[s->top] = item;
        s->top++;
    }
}

// Return the item that's on top of the stack 
// Move the top down one.
int stackPop(Stack s) {
    int stackItem;
    if (s->top <= 0) {
        // stack is empty, cannot pop
        printf("Stack has no elements, and cannot pop.\n");
        exit(1);
    } else {
        s->top--;
        stackItem = s->stackItems[s->top];
    }
    
    return stackItem;
}





Resource created Tuesday 10 November 2020, 01:19:38 PM.

file: stack_alternate.c


Back to top

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