题目:Merge Two Sorted Lists 合并两个有序的链表
难度:简单
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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
题意解析:
将两个有序的链表合并返回新的链表,新链表应该通过将前两个链表的节点拼接在一起来创建。
解题思路一:
利用递归的思路,依次遍历每个节点,判断当前l1的value和l2的value,如果l1的比较小,那么l1.next指向l1.next和l2进行合并的值,最后返回l1,如果l2比较小则反之。
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val <= l2.val){
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}else{
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}
提交代码之后:
Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.
Memory Usage: 37 MB, less than 97.95% of Java online submissions for Merge Two Sorted Lists.