leetcode
题目描述将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
代码
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode temp = new ListNode(-1);
ListNode res = temp;
while(list1 != null && list2 != null){
if(list1.val <= list2.val){
temp.next = list1;
temp = temp.next;
list1 = list1.next;
}else{
temp.next = list2;
temp = temp.next;
list2 = list2.next;
}
}
if(list1 != null){
temp.next = list1;
}
if(list2 != null){
temp.next = list2;
}
return res.next;
}
}
结果



