题目
将两个升序链表合并为一个新的 升序 链表并返回. 新链表是通过拼接给定的两个链表的所有节点组成的.
https://leetcode-cn.com/problems/merge-two-sorted-lists/
思路
- 链表为空的临界值判断
- 声明一个假头节点, 维护当前指针
- 循环判断当两个链表都不为空时, 进行 next 赋值, 并且移动原链表和新链表指针
- 循环结束后, 判断链表是否为空, 继续把剩下的链表接上
- 最终返回假头节点的 next
代码
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
// 空判断
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
// 临时头节点, 之后方法返回值是 head.next
ListNode head = new ListNode(0);
// 合并后链表的末尾节点
ListNode curr = head;
// 循环判断都不为空, 则比较值, 赋值给 curr.next, 再移动原链表和结果链表的末尾指针
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
curr.next = list1;
curr = curr.next;
list1 = list1.next;
} else {
curr.next = list2;
curr = curr.next;
list2 = list2.next;
}
}
// 当一个链表为空时, 把剩下的元素接上
curr.next = (list1 == null) ? list2 : list1;
// 最终返回虚拟头节点的 next
return head.next;
}