我试图理解反向链接列表的递归方式。
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。最后一个节点不指向空可以吗?或者我错过了什么?
最佳答案
你就是榜样。但是,当您删除行 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。
关于java - 递归反向链表,最后一个节点应该指向null吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61165678/