
思路分析:
同时遍历两个链表,比较它们对应位置的值,将较小值的节点添加到结果链表的下一个节点中,当一个节点被添加到结果链表后,将对应链表中的节点向后移一位。体现在代码中如下:
if(v1 <= v2){
curr.next = list1;
list1 = list1.next;
}else {
curr.next = list2;
list2 = list2.next;
}
curr = curr.next;
在循环终止的时候,链表 list1 和 list2 至多有一个是非空的。由于输入的两个链表都是有序的,所以不管哪个链表是非空的,它包含的所有元素都比前面已经合并链表中的所有元素都要大。这意味着我们只需要简单地将非空链表拼接在结果链表后面,并返回合并链表即可。
体现在代码上为:
curr.next = (list1 == null) ? list2 : list1;
最终返回链表,即虚拟头节点的下一个节点
return dummy.next;
完整代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode();
ListNode curr = dummy;
//只要有一个链表为空,那么就不需要合并了,直接返回非空的链表
while(list1 != null && list2 != null){
int v1 = list1.val;
int v2 = list2.val;
if(v1 <= v2){
curr.next = list1;
list1 = list1.next;
}else{
curr.next = list2;
list2 = list2.next;
}
curr = curr.next;
}
curr.next = (list1 == null) ? list2 : list1;
return dummy.next;
}
}

No responses yet