题解 | #合并两个排序的链表#在while循环中完成所有
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null){
return list2;
}
if(list2 == null){
return list1;
}
//先找到头部小的那个链表的节点
ListNode smallNode = list1;
if(list1.val > list2.val){
smallNode = list2;
list2 = list2.next;
} else {
list1 = list1.next;
}
ListNode head = smallNode;
while(list1 != null || list2 != null){
if(list1 == null){
head.next = list2;
break;
}
if(list2 == null){
head.next = list1;
break;
}
if(list1.val > list2.val){
head.next = list2;
head = head.next;
list2 = list2.next;
} else {
head.next = list1;
head = head.next;
list1 = list1.next;
}
}
return smallNode;
}
}

查看3道真题和解析