1、题目
2、解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode tmp1 = l1;
ListNode tmp2 = l2;
ListNode dummy = new ListNode(0);
ListNode preNode = dummy;
while (tmp1 != null && tmp2 != null) {
if (tmp1.val >= tmp2.val) {
preNode.next = tmp2;
tmp2 = tmp2.next;
} else {
preNode.next = tmp1;
tmp1 = tmp1.next;
}
preNode = preNode.next;
}
// 最后谁剩余
preNode.next = tmp1 != null ? tmp1 : tmp2;
return dummy.next;
}
}
时间复杂度O(m+n),空间复杂度O(1)