Reverse a Linked List

This problem asks you to reverse a singly linked list. An example input is given as 1->2->3->4->5, and the expected output is 5->4->3 ->2->1.

Problem

Reverse a singly linked 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;
};

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 solves the problem. The approach is to reverse the linked list by changing the next pointers of each node. The solution first sets the next pointer of the head node to NULL, then iterates through the linked list, setting the next pointer of each node to the previous node, and finally returns the previous node (which is the new head of the reversed linked list).

Evaluated at: 2022-11-19 06:15:58