简体   繁体   English

java中如何获取LinkedList的头节点?

[英]How to get the head node of LinkedList in java?

This is leetcode 21 problem to merge two linkedlist, I try my best solution that is given below but still I'm getting error?这是合并两个链表的 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;
        
        
        
        
    }
}

Line 14: error: cannot find symbol symbol: Variable head第 14 行:错误:找不到符号符号:变量头

How can we access the head of the linkedlist?我们如何访问链表的头部?

We can also do it recursively:我们也可以递归地进行:

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM