Reverse a Singly 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.


Reverse a singly linked list.
Example input:
Example output:


This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
# = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        # iterative solution
        prev = None
        curr = head
        while curr:
            next =
   = prev
            prev = curr
            curr = next
        return prev
        # recursive solution
        # if not head or not
        #     return head
        # p = self.reverseList(
        # = head
        # = None
        # return p

A.I. Evaluation of the Solution

The candidate's solution correctly implements a solution to reverse a singly linked list, both iteratively and recursively. The iterative solution is more efficient, however, both solutions are correct. The candidate demonstrates a good understanding of linked lists and how to reverse them.

Evaluated at: 2022-12-07 06:15:42