题目链接 => 戳这里
解法
/**
* 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 mergeListHead = new ListNode(0);
ListNode newHead = mergeListHead;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
newHead.next = l1;
l1 = l1.next;
} else {
newHead.next = l2;
l2 = l2.next;
}
// 注意新链表节点要转移到下一个节点
newHead = newHead.next;
}
// 两个链表中最多只有一个链表会没有遍历到最后的节点
// 如何没到最后,直接加在新链表的后面即可,因为本来就是有序的
if (l1 != null) {
newHead.next = l1;
} else if (l2 != null) {
newHead.next = l2;
}
// 返回头节点的下个节点
return mergeListHead.next;
}
}