// Arup Guha
// 4/29/2022
// Solution to Spring 2022 COP 3502 Final Exam Question 9

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int data;
    struct node* next;
} node;

void addIndex(node* front);
node* insertFront(node* list, int val);
void printList(node* list);
void freeList(node* list);

int main(void) {

    // Set up a list.
    node* list = NULL;
    list = insertFront(list, 3);
    list = insertFront(list, 8);
    list = insertFront(list, 6);
    list = insertFront(list, 7);
    list = insertFront(list, 12);
    list = insertFront(list, 15);
    list = insertFront(list, 2);

    // See what it looks like.
    printList(list);

    // Run our function.
    addIndex(list);

    // Check that it worked.
    printList(list);

    // Free memory.
    freeList(list);

    return 0;
}

// Adds i to the ith item in the linked list pointed to by front, starting with 1.
void addIndex(node* front) {

    // What we add.
    int i = 1;

    // Go through the list.
    while (front != NULL) {

        // Add i.
        front->data += i;

        // Update i and go to the next item in the list.
        i++;
        front = front->next;
    }
}

// Inserts a node storing val at the front of the list pointed to be list and returns a pointer
// to the new front of the list.
node* insertFront(node* list, int val) {
    node* tmp = malloc(sizeof(node));
    tmp->data = val;
    tmp->next = list;
    return tmp;
}

// Prints the items in the list pointed to by list.
void printList(node* list) {
    while (list != NULL) {
        printf("%d ", list->data);
        list = list->next;
    }
    printf("\n");
}

// Frees the dynamically allocated memory in the list pointed to by list (all nodes).
void freeList(node* list) {
    if (list == NULL) return;
    freeList(list->next);
    free(list);
}
