// A simple Linked List demo
// Marc Chee April 2019

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

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

struct node *createNode (int data, struct node *next);

int main (void) {
    // head will always point to the first element of our list
    struct node *head = createNode(1, NULL);
    head = createNode(2, head);
    head = createNode(3, head);
    head = createNode(4, head);
    head = createNode(5, head);
    
    return 0;
}

// Create a node using the data and next pointer provided
// Return a pointer to this node
struct node *createNode(int data, struct node *next) {
    struct node *n;
    // allocate the memory for a single node
    n = malloc(sizeof (struct node));
    if (n == NULL) {
        // malloc returns NULL if there isn't enough memory
        // terminate the program
        fprintf(stderr, "out of memory\n");
        exit(1);
    }
    n->data = data;
    n->next = next;
    return n;
}

Resource created Tuesday 09 April 2019, 12:29:09 AM, last modified Wednesday 10 April 2019, 10:32:08 AM.

file: linkedlist.c


Back to top

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