【发布时间】:2021-05-03 16:43:49
【问题描述】:
我正在尝试掌握递归的概念并尽可能多地进行练习,但是当涉及到更困难的问题(例如递归函数以及在链接列表和树中使用它)时,我似乎完全被它难住了。
在这里,我只是想反转一个链表,在此处提供的 leetcode 问题中使用递归 - https://leetcode.com/problems/merge-two-sorted-lists/。 虽然有可用的解决方案,但我想知道为什么我的代码不起作用,因为当我打印出正确的值似乎出现但我不知道为什么它没有链接适当地。 任何帮助表示赞赏。
谢谢
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution
{
static ListNode temp = new ListNode();
public ListNode mergeTwoLists(ListNode l1, ListNode l2)
{
//Base case, return temp listNode
if(l1 == null && l2 == null) return temp;
//If l1 has been used up and l2 not
if(l1 == null && l2 != null)
{
temp.next = l2;
l2 = l2.next;
}
//If l2 has been used up and l1 not
if(l2 == null && l1 != null)
{
temp.next = l1;
l1 = l1.next;
}
//If both nodes exist
if(l2 != null && l1 != null)
{
if(l2.val <= l1.val)
{
temp.next = l2;
l2 = l2.next;
}
else
{
temp.next = l1;
l1 = l1.next;
}
}
System.out.println(temp.val + " next " + temp.next.val);
temp = temp.next;
return mergeTwoLists(l1,l2);
}
}
【问题讨论】:
-
您是要合并列表还是反转它们?还有
bad是从哪里来的? -
合并列表,抱歉,这是我忘记删除的无关变量
标签: java recursion linked-list