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.

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 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
#         self.next = None

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