题目详情见:https://leetcode-cn.com/problems/merge-two-sorted-lists/
方法一:
同时比较遍历两个链表,将较小元素追加到结果链表,最后将剩余的链表追加到结果链表末尾。
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode first = new ListNode(0); //结果链表的辅助头节点
ListNode point = first; //遍历用指针
while (l1 != null && l2 != null) {//较小元素追加
if (l1.val < l2.val) {
point.next = l1;
l1 = l1.next;
point = point.next;
}
else {
point.next = l2;
l2 = l2.next;
point = point.next;
}
}
//有剩余的链表追加到末尾
//该语句可优化为:point.next = (l1 == null) ? l2 : l1;
if (l1 != null) {
point.next = l1;
}
if (l2 != null) {
point.next = l2;
}
return first.next;
}
}
时间复杂度:O(n + m); 空间复杂度:O(1);
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
else if (l2 == null) {
return l1;
}
else if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}
else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}