1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Python - Reverse Linked List Issue

Discussão em 'Python' iniciado por Stack, Setembro 12, 2024.

  1. Stack

    Stack Membro Participativo

    I have been working on the reverse linked list method for a long time and I am trying to understand why it is wrong but I can't seem to get it. The following is my function.

    def reverse(self, head):
    if head is None or head.next is None:
    return head

    prev = None
    current = head

    while current is not None:
    temp = current
    current.next = prev
    prev = temp
    current = prev.next

    return prev


    I thought the above reverse function should work. Example SLL: 1 -> 2 -> 3 -> None
    My thought process:

    1. Set temp to reference to the current which is the head of the linked list. Thus, temp.val = 1 and temp.next.val = 2.
    2. current.next = prev means that the current is now pointing to None.
    3. prev = temp means that prev.val = 1 and prev.next.val = 2
    4. current = prev.next means that current.val = 2 and current.next.val = 3

    Is my thought process correct? If not, which step is incorrect? I also searched up the "correct" way of doing this where

    while current is not None:
    temp = current.next
    current.next = prev
    prev = current
    current = temp


    This works but I want to understand why my way of doing it is incorrect. I don't want to memorise blindly.

    Continue reading...

Compartilhe esta Página