class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode cur = new ListNode(0);
ListNode sum = cur;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
sum.next = list1;
sum = sum.next;
list1 = list1.next;
} else {
sum.next = list2;
sum = sum.next;
list2 = list2.next;
}
}
if (list1 == null) {
sum.next = list2;
} else {
sum.next = list1;
}
return cur.next;
}
}
定义一个cur链表,再定义一个sum链表指向cur。
如果说list1和list2有一个为空,那么循环就结束,并把sum链表头指向不为空的那个链表。
如果list1的链表值小于list2的链表值,就将sum的next值指向list1,并将sum和list都向后移一个长度。
最后返回cur.next即可