这是leetcode 21合并两个链表的问题,我尝试了下面给出的最佳解决方案但我还是犯了错误?
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2)
{
ListNode one = l1.head;
ListNode two = l2.head;
LinkedList res=new LinkedList();
while(one.val!= null && two.val!= null)
{
if(one.val<=two.val)
{
res.addLast(one.val);
one=one.next;
}
else
{
res.addLast(two.val);
two=two.next;
}
}
//if second list finish
while(one.val!=null)
{
res.addLast(one.val);
one=one.next;
}
//if first list finish
while(two.val!=null)
{
res.addLast(two.val);
two=one.next;
}
return res;
}
}
第14行:错误:找不到符号符号:可变头
我们如何访问链接列表的标题?
我们也可以递归地执行:
public class Solution {
public static final ListNode mergeTwoLists(
final ListNode l1,
final ListNode l2
) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
final ListNode merged;
if (l1.val < l2.val) {
merged = l1;
merged.next = mergeTwoLists(l1.next, l2);
} else {
merged = l2;
merged.next = mergeTwoLists(l1, l2.next);
}
return merged;
}
}