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.

Problem

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

Solution

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):
        self.data = data
        self.next = None

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

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

    def print_list(self):
        current = self.head
        while current:
            print(current.data)
            current = current.next

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

ll.print_list()
print("\n")
ll.reverse()
ll.print_list()

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