thiagowfx's avatar

Β¬ just serendipity πŸ€ (not just serendipity)

ByteByteGo: Linked List Reversal

β€’ 115 words β€’ 1 min β€’ updated

ByteByteGo: Linked List Reversal:

Recursive #

python
from ds import ListNode

"""
Definition of ListNode:
class ListNode:
    def __init__(self, val=None, next=None):
        self.val = val
        self.next = next
"""

def linked_list_reversal(head: ListNode) -> ListNode:
    if head is None or head.next is None:
        return head

    new_head = linked_list_reversal(head.next)

    head.next.next = head
    head.next = None

    return new_head

Iterative #

python
from ds import ListNode

"""
Definition of ListNode:
class ListNode:
    def __init__(self, val=None, next=None):
        self.val = val
        self.next = next
"""

def linked_list_reversal(head: ListNode) -> ListNode:
    if head is None or head.next is None:
        return head

    prev = None

    while head is not None:
        next_node = head.next

        head.next = prev

        prev = head
        head = next_node

    return prev