from algorithms.list_node import ListNode

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    # recursion solution
    # time:  O(n)
    # space: O(n)
    def reverseListR(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head

        p = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return p

    # iterative solution
    # time:  O(n)
    # space: O(1)
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        prev = head
        node = prev.next
        prev.next = None
        while node:
            tmp = node.next
            node.next = prev
            prev = node
            if not tmp:
                break
            node = tmp
        return node
