Переверните связанный список, передав заголовок через функцию

Чтобы перевернуть связанный список путем передачи его заголовка через функцию, вы можете использовать различные методы. Вот несколько примеров:

Метод 1: итеративный подход

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
def reverse_linked_list(head):
    if head is None or head.next is None:
        return head
    prev = None
    current = head
    while current:
        next_node = current.next
        current.next = prev
        prev = current
        current = next_node
    return prev

Метод 2: рекурсивный подход

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
def reverse_linked_list(head):
    if head is None or head.next is None:
        return head
    rest = reverse_linked_list(head.next)
    head.next.next = head
    head.next = None
    return rest

Метод 3: стековый подход

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
def reverse_linked_list(head):
    if head is None or head.next is None:
        return head
    stack = []
    current = head
    while current:
        stack.append(current)
        current = current.next
    head = stack.pop()
    current = head
    while len(stack) > 0:
        node = stack.pop()
        current.next = node
        current = current.next
    current.next = None
    return head

Это всего лишь несколько примеров того, как можно перевернуть связанный список, передав его заголовок через функцию. Существуют и другие методы, но они должны стать хорошей отправной точкой.