题目描述
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
思路
使用2个指针分别遍历每个链表,向后移动val值较小的指针。当某一个指针为null
后,直接让链表指向另一个指针即可。
代码
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {return l2;}
if (l2 == null) {return l1;}
ListNode head = new ListNode(0);
ListNode tail = head;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
tail.next = l1;
l1 = l1.next;
} else {
tail.next = l2;
l2 = l2.next;
}
tail = tail.next;
}
tail.next = l1 == null ? l2 : l1;
// 由于head处是自定义的new ListNode(0),所以此时返回head.next
return head.next;
}