79492266

Date: 2025-03-07 12:08:56
Score: 0.5
Natty:
Report link

Let's see the reverseList() function in action using memory_graph:

import memory_graph as mg # see link above for install instructions

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def build_list(n = 5):
    head = None
    for i in range(n, 0, -1):
        head = ListNode(i, head)
    return head

def reverseList(head: ListNode) -> ListNode:
    cur , pre = head, None
    while cur:
        tmp = cur.next  
        cur.next = pre 
        pre = cur
        cur = tmp
        mg.block(mg.show, mg.get_call_stack())  # graph each reverse step
    return pre

head = build_list()                      # build a test linked list
mg.block(mg.show, mg.get_call_stack())   # graph the test list
head = reverseList(head)                 # reverse list
mg.show(mg.get_call_stack())             # graph the reversed list

Pressing <Enter> a number of times now results in:

reverse linked list

Full disclosure: I am the developer of memory_graph.

Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: bterwijn