Reversing a Linked List

Reversing a linked list involves iterating through the list and reversing the order of the nodes. This can be done by changing the next pointers of the nodes so that they point to the previous node in the list.


Given a 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


This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
# Solution:
# The optimal solution is to use a stack to store the nodes in reverse order.
# This is optimal because it uses O(n) space and O(n) time.

class Node:
    def __init__(self, data): = data = None

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

    def reverse(self):
        stack = []
        current = self.head
        while current:
            current =
        self.head = stack.pop()
        current = self.head
        while stack:
   = stack.pop()
            current = = None

    def print_list(self):
        current = self.head
        while current:
            current =

ll = LinkedList()
ll.head = Node(1)
second = Node(2)
third = Node(3)
fourth = Node(4 )
fifth = Node(5) = second = third = fourth = fifth


A.I. Evaluation of the Solution

The candidate's solution is correct and uses O(n) space and time. The candidate's approach is to use a stack to store the nodes in reverse order.

Evaluated at: 2022-11-23 06:16:23