递归地反向链表,最后一个节点应该指向null吗



我正在尝试理解反向链表的递归方法。

public ListNode reverseList2(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList2(head.next);
head.next.next = head;
head.next = null;
return newHead;
}

反向链表

1->2->3->null

答案是

3->2->1->null

根据我的理解,最后一个节点应该指向null。但在这个递归函数中,当它反转最后一个节点时,它并没有将其指向null。可以吗,最后一个节点不指向null?还是我错过了什么?

您就是示例作品。然而,当您删除线路head.next = null;时,它不起作用

public ListNode reverseList2(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList2(head.next);
head.next.next = head;
return newHead;
}

在那里它变成了一个圆形链表,尾部指向头部。你可能不小心忘记了那条线,然后尾巴没有指向null。这是因为这一行确保了如果你在最后,下一行等于null。

最新更新