LeetCode 21. 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.


题目标签:Linked List

  题目给了我们两个lists,让我们有序的合并两个 lists。

  这题利用递归可以从list 的最后开始向前链接nodes,代码很简洁,清楚。

Java Solution:

Runtime beats 74.35% 

完成日期: 06/09/2017

关键词:singly-linked list

关键点:利用递归从最后开始链接nodes

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution 
10 {
11     public ListNode mergeTwoLists(ListNode l1, ListNode l2) 
12     {
13         if(l1 == null)
14             return l2;
15         if(l2 == null)
16             return l1;
17         
18         if(l1.val < l2.val)
19         {
20             l1.next = mergeTwoLists(l1.next, l2);
21             return l1;
22         }
23         else
24         {
25             l2.next = mergeTwoLists(l1, l2.next);
26             return l2;
27         }
28     }
29     
30 }

参考资料:

https://discuss.leetcode.com/topic/45002/java-1-ms-4-lines-codes-using-recursion

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

原文地址:https://www.cnblogs.com/jimmycheng/p/7883000.html