Reversing a singly linked list.

This problem asks you to reverse the order of the nodes in 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 nodes in the list.
Example input:
1->2->3->4->5
Example output:
5->4->3->2->1

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node

    def printList(self):
        temp = self.head
        while(temp):
            print(temp.data)
            temp = temp.next

    def reverse(self):
        prev = None
        current = self.head
        while(current is not None):
            next = current.next
            current.next = prev
            prev = current
            current = next
        self.head = prev

llist = LinkedList()
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)

print("Given Linked List")
llist.print List()
llist.reverse()
print("\nReversed Linked List")
llist.printList()

A.I. Evaluation of the Solution

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

Evaluated at: 2022-11-11 04:15:54