思路: 创建一个临时的节点,命名傀儡节点,可以理解成临时的头节点,newHead,list1和list2的两两元素比较,小的连接newHead(升序)newHead的路径(蓝色)就是连接后的路径
public class Solution {public class ListNode {int val;ListNode next = null;ListNode(int val) {this.val = val;}}public ListNode mergeTwoLists(ListNode list1, ListNode list2) {if(list1==null)return list2;if(list2==null)return list1;ListNode cur=new ListNode(-1);//傀儡节点,相当于临时的头节点ListNode tmp=cur;//防止改变cur节点while (list1!=null && list2!=null){if(list1.val>list2.val){tmp.next=list2;list2=list2.next;tmp=tmp.next;}else{tmp.next=list1;list1=list1.next;tmp=tmp.next;}}if (list1 !=null)tmp.next=list1;if (list2 !=null)tmp.next=list2;return cur.next;}
}