我正在开发一个使用递归来反转链表的Python程序.我已经实现了反转函数,并添加了打印语句来帮助我理解该过程.但是,当我包含某些打印语句时,程序挂起并且无法完成.这种逆转似乎在没有这些印刷声明的情况下运作良好.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __repr__(self):
next = self.next
val = self.val
out = f"ListNode({val}, "
count_paren = 1
while next is not None:
val = next.val
out += f"ListNode({val}, "
next = next.next
count_paren += 1
out += f"{next}"
out += count_paren * ")"
return out
def reverse(head):
if not head or not head.next:
return head
print("1 HEAD", head)
new_head = reverse(head.next)
print("2 NEW_HEAD", new_head)
head.next.next = head
print("3 HEAD", head)
print("4 NEW_HEAD", new_head)
head.next = None
print("5 HEAD", head)
print("6 NEW_HEAD", new_head)
return new_head
lst = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
print(lst)
print(reverse(lst))
不使用PRINT语句:
print("3 HEAD", head)
print("4 NEW_HEAD", new_head)
这种反转效果很好.但是,如果我取消对这些行的注释,程序就会挂起.
对于为什么会发生这种情况,以及我如何修改打印语句以更好地理解该过程而不会导致挂起,我将不胜感激.我使用的是PYTHON版本的3.11.2
.