Reverse a Linked List

This problem asks you to reverse a linked list. An example input and output is given.

Problem

Given a linked list, reverse the nodes of the list and return the new head node.
Example input:
1 -> 2 -> 3 -> 4 -> 5
Example output:
5 -> 4 -> 3 -> 2 -> 1

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>

using namespace std;

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

Node *reverse(Node *head) {
    Node *prev = NULL;
    Node *curr = head;
    Node *next = NULL;

    while (curr != NULL) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }

    return prev;
}

void printList(Node *head) {
    Node *curr = head;
    while (curr != NULL) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
}

int main() {
    Node *head = new Node;
    head->data = 1;
    head->next = new Node;
    head->next->data = 2;
    head->next->next = new Node;
    head->next->next->data = 3;
    head->next ->next->next = new Node;
    head->next->next->next->data = 4;
    head->next->next->next->next = new Node;
    head->next->next->next->next->data = 5;
    head->next->next->next->next->next = NULL;

    printList(head);
    head = reverse(head);
    printList(head);

    return 0;
}

A.I. Evaluation of the Solution

This solution is complete and correctly solves the problem. The approach is to reverse the nodes in the list by changing the pointers so that the next node points to the previous node.

Evaluated at: 2022-11-25 18:15:38