1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Python, linked list

Discussão em 'Python' iniciado por Stack, Março 7, 2025.

  1. Stack

    Stack Membro Participativo

    Here is a question from leetcode:


    Define a function, input the head node of a linked list, invert the linked list.

    example:

    • input: 1->2->3->4->5->NULL
    • output: 5->4->3->2->1->NULL
    ​

    Here is the official answer to it:

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

    class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
    cur , pre = head, None
    while cur:
    tmp = cur.next
    cur.next = pre
    pre = cur
    cur = tmp
    return pre


    I want to ask what does the line while cur: mean? Does it transverse the whole linked list? I tried to replace it with while head:, why it doesn't work since cur == head?

    Continue reading...

Compartilhe esta Página