Tag:list
Difficulty:Easy
Problem
21. Merge Two Sorted Lists
You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
Solution
链表节点插入问题
先确定首元素较小的链表作为返回结果,遍历另一个链表元素在合适位置插入即可。
注意:假设以链表1为底,最后判断若链表2不为空,附在结果后面。
public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
if (l1==null){
return l2;
}
if (l2==null){
return l1;
}
ListNode l = l1.val <= l2.val ? l1 : l2; // 较小的链
ListNode p = l, pre = l;
ListNode q = l1.val <= l2.val ? l2 : l1; // 较大的
while (p != null && q != null) {
while (p != null && p.val < q.val) {
pre = p;
p = p.next;
}
ListNode tmp = q.next;
q.next = pre.next;
pre.next = q;
pre = pre.next;
q = tmp;
}
if (q != null) {
pre.next = q;
}
return l;
}