题目
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
分析
1 很早之前做过类似的合并
2 分为两步 1 while循环里判断此次结点的下一个结点应该指向谁
2 最后再接上仍然存在结点的链表
3 注意一开始仍然要用dummy 存一下, Newstart在一直变化
代码
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode newStart = new ListNode(0);
ListNode dummy = newStart;
while (l1!= null && l2 != null){
if(l1.val > l2.val){
newStart.next = l2;
l2 = l2.next;
}else {
newStart.next = l1;
l1 = l1.next;
}
newStart = newStart.next;
}
newStart.next = l1 == null ? l2 : l1;
return dummy.next;
}