Leetcode 21(Java)

来源:互联网 发布:7.62*63步枪子弹数据 编辑:程序博客网 时间:2024/06/08 05:35

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

题目很简单有很简短,实际上对于链表的题目很容易想到递归的方法。新建一个头节点,不断拿两个链表的节点比较,谁小就链接上去。然后那个链表往下跳一个节点,AC码如下:

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        if(l1==null)return l2;        if(l2==null)return l1;        ListNode resultHead;        if(l1.val<l2.val){            resultHead=l1;            resultHead.next=mergeTwoLists(l1.next,l2);        }else{            resultHead=l2;            resultHead.next=mergeTwoLists(l1,l2.next);        }        return resultHead;    }