思路: 1.新创建个节点,比较两个list1 和 list2 当前节点,不断遍历,将新创建的节点指向比较当中的最小的节点 2.肯定有一个节点没有遍历完,需要判断一下,直接next指向后面不为空的节点
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 newHead = new ListNode(-1);
ListNode currentNode = newHead;
ListNode cur1 = list1, cur2 = list2;
while(cur1 != null && cur2 != null){
if(cur1.val < cur2.val){
currentNode.next = cur1;
cur1 = cur1.next;
}else{
currentNode.next = cur2;
cur2 = cur2.next;
}
currentNode = currentNode.next;
}
if(cur1 == null && cur2 != null){
currentNode.next = cur2;
}
if(cur1 != null && cur2 == null){
currentNode.next = cur1;
}
return newHead.next;
}
}