class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//辅助节点
ListNode dummy = new ListNode(-1);
for(ListNode cur = dummy; l1!= null || l2!=null;) {
if(l1 == null){
cur.next = l2;
return dummy.next;
}
if(l2 == null) {
cur.next = l1;
return dummy.next;
}
if(l1.val< l2.val) {
cur.next = l1;
l1 = l1.next;
}else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
return dummy.next;
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
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 {
cur.next =l2;
l2 = l2.next;
}
cur= cur.next;
}
if(l1!= null)
cur.next = l1;
if(l2 != null)
cur.next = l2;
return dummy.next;
}
}
21. 合并两个有序链表
最新推荐文章于 2024-09-28 20:24:08 发布