Leetcode 21(Java)

xiaoxiao2021-02-28  90

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; }
转载请注明原文地址: https://www.6miu.com/read-36999.html

最新回复(0)