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:
Full disclosure: I am the developer of memory_graph.