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

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

#include "stack.h"

struct stackInternals {
    struct node *top;
};

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

// 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 = NULL;
    return s;
}

// Add an element on top of the stack
void stackPush(stack s, int item) {
    struct node *n = malloc(sizeof (struct node));
    if (n == NULL) {
        printf("Cannot allocate memory for a node.\n");
        exit(1);
    }
    n->data = item;
    n->next = s->top;
    s->top = n;
}

// Remove the top element from the stack
int stackPop(stack s) {
    if(s->top == NULL) {
        printf("Stack is empty, cannot pop.\n");
        exit(1);
    }
    // keep a pointer to the node so we can free it
    struct node *n = s->top;
    int item = n->data;
    s->top = s->top->next;
    free(n);
    return item;
}

Resource created Tuesday 23 April 2019, 02:03:37 AM, last modified Wednesday 24 April 2019, 03:47:26 PM.

file: stackLL.c


Back to top

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