题目:https://leetcode-cn.com/problems/merge-two-sorted-lists/
解法附注释
/**
* 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 l1, ListNode l2) {
// 特殊判断
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
ListNode dummy = new ListNode(-1);// 哨兵节点
ListNode cur = dummy;// 当前指针
while(l1!=null && l2!=null){
if(l1.val<=l2.val){
cur.next=l1;
l1=l1.next;// 指针后移
}else if(l1.val>l2.val){
cur.next = l2;
l2=l2.next;// 指针后移
}
cur=cur.next;// 指针后移
}
// 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
cur.next = l1==null ? l2: l1;
return dummy.next;
}
}