// Arup Guha
// 3/24/2026
// Returns the reverse of a given linked list in a new physical list.
// Written as practice for Exam 2 COp 3502

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int data;
    struct node* next;
} node;

node* insertFront(node* list, int val);
node* newrevlist(node* front);
void print(node* list);

int main() {

    // Put some stuff in a list.
    node* mine = NULL;
    mine = insertFront(mine, 3);
    mine = insertFront(mine, 2);
    mine = insertFront(mine, 8);
    mine = insertFront(mine, 6);
    mine = insertFront(mine, 5);
    print(mine);

    // Test our function.
    node* rev = newrevlist(mine);
    print(rev);
    print(mine);

    return 0;
}

// Prints contents in the list pointed to by list.
void print(node* list) {
    while (list != NULL) {
        printf("%d ", list->data);
        list = list->next;
    }
    printf("\n");
}

// Inserts a node storing val to the front of the list pointed to by 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;
}

// Solution to the practice exam question.
node* newrevlist(node* front) {

    // Answer will be here.
    node* mine = NULL;

    // Loop through the input list.
    while (front != NULL) {

        // Make the new node, link it to mine.
        node* tmp = malloc(sizeof(node));
        tmp->data = front->data;
        tmp->next = mine;

        // Update mine.
        mine = tmp;

        // Move to the next node in our input list.
        front = front->next;
    }

    return mine;
}
