Given a singly linked list, reverse the order of the elements in the list.
Reverse a singly linked list. Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
# 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: prev = None curr = head while curr: next = curr.next curr.next = prev prev = curr curr = next return prev
This is a good solution that correctly reverses a singly linked list. The approach is clear and easy to follow.
Evaluated at: 2022-11-22 14:15:41