Reversing a Linked List

This problem asks you to reverse the order of a singly linked list. For example, if the input list is 1->2->3->4->5, the output should be 5 ->4->3->2->1.

Problem

Given a singly linked list, reverse the order of the list.
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;
};

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

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

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

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);
    reverseList(head);
    printList(head);

    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution correctly reverses the order of a singly linked list. The approach is clear and easy to follow.

Evaluated at: 2022-11-18 23:34:30