[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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

题目

合并两个链表

思路

用dummy, 因为需要对头结点进行操作

代码

 1 /* 
 2 Time: O(min(m,n)) 因为一旦l1或l2有一方先遍历完,循环结束
 3 Space: O(1) 因为没有额外多开空间
 4 */
 5 class Solution {
 6     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
 7         // corner case
 8         if (l1 == null) return l2;
 9         if (l2 == null) return l1;
10         
11         ListNode dummy = new ListNode(-1);
12         ListNode p = dummy;
13         
14         while(l1 != null && l2 != null){
15             if (l1.val > l2.val){
16                 p.next = l2; 
17                 l2 = l2.next;
18             }else{
19                 p.next = l1; 
20                 l1 = l1.next;  
21             }
22             p = p.next;
23         }
24         p.next = l1 != null ? l1 : l2;
25         return dummy.next;
26     }
27 }
原文地址:https://www.cnblogs.com/liuliu5151/p/9828158.html