// Arup Guha
// 10/10/2023
// Code for COP 3502 Exam 1 A Section 1 Question 1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node {
    char name[50];
    int ucfid;
    struct node* next;
} node;

node* change(node* sList, char newname[], int newid);
void print(node* list);
void freelist(node* list);

int main() {

    node* mine = NULL;

    // Allows the user to test the change function...
    while (1) {

        int quit;
        printf("do you want to quit?(1=yes)?\n");
        scanf("%d", &quit);
        if (quit == 1) break;

        char n[50];
        int d;
        printf("Enter name and id.\n");
        scanf("%s%d", n, &d);

        mine = change(mine, n, d);
        print(mine);
    }

    // Clean up.
    freelist(mine);
    return 0;
}

// Returns a pointer to the potentially changed list, where newname's id is changed to newid.
node* change(node* sList, char newname[], int newid) {

    // Temp poointer since I can't lose sList.
    node* tmp = sList;

    // Go through the list looking for this person.
    while (tmp != NULL) {

        // This isn't them, keep on going...
        if (strcmp(tmp->name, newname) != 0) {
            tmp = tmp->next;
            continue;
        }

        // If we get here, we found them, change id and return.
        tmp->ucfid = newid;
        return sList;
    }

    // Make a new node, copy in the info.
    node* newn = malloc(sizeof(node));
    strcpy(newn->name, newname);
    newn->ucfid = newid;

    // Link to rest of the list.
    newn->next = sList;

    // This is the new front of the list.
    return newn;

}

// Prints all items in the linked list pointed to by list.
void print(node* list) {
    while (list != NULL) {
        printf("%s --> %d\n", list->name, list->ucfid);
        list = list->next;
    }
}

// Free all the nodes in the linked list pointed to by list.
void freelist(node* list) {
    if (list == NULL) return;
    freelist(list->next);
    free(list);
}
