#include "linked_list.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//function prototypes
Node *init_node(void);

Node *init_node(void) {
    Node *n = malloc(sizeof(*n));
    if (n == NULL) {  // always make sure malloc succeeded
        fprintf(stderr, "init_node: malloc failed\n");
        exit(1);
    }
    n->data = NULL;
    n->next = NULL;
    return n;
}

Node *create_list(void) {
    return init_node();
}

// if you're having a hard time thinking through how I've done this,
// it might help to write out what happens for a small list
void destroy_list(Node *list) {
    if (list->next != NULL) {
        // recursively destroy the rest of the list before we destroy
        // this node
        destroy_list(list->next);  
    }
    if (list->data != NULL) {
        free(list->data);
    }
    free(list);
}

Node *add_node(Node *list, char *str) {
    // get to the end of the list
    while (list->next != NULL) {
        list = list->next;
    }
    list->next = init_node();  // setup new node
    if (str != NULL) {
        // we make a copy of str on the heap, so we can be sure it
        // will stick around
        list->next->data = malloc(strlen(str) + 1);
        strncpy(list->next->data, str, strlen(str) + 1);
    } else {
        list->next->data = NULL;
    }
    return list->next;  // return the end of the list
}

void print_list(Node *list) {
    while (list->next != NULL) {
        printf("%s -> ", list->data);
        list = list->next;
    }
    printf("%s\n", list->data);
}