Merge two sorted ed 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
递归和迭代:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode head = new ListNode(0);
if(l1.val < l2.val){
head = l1;
head.next = mergeTwoLists(l1.next, l2);
}else{
head = l2;
head.next = mergeTwoLists(l2.next, l1);
}
return head;
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode dummy = new ListNode(0);
ListNode node = dummy;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
node.next = l1;
node = node.next;
l1 = l1.next;
}else{
node.next = l2;
node = node.next;
l2 = l2.next;
}
}
if(l1 != null){
node.next = l1;
}else{
node.next = l2;
}
return dummy.next;
}
继续阅读与本文标签相同的文章
上一篇 :
reverse函数
-
第三讲,Ceph内部构件
2026-05-18栏目: 教程
-
日本发明AI女友,中国却发明AI主持人,这就是差距!
2026-05-18栏目: 教程
-
《华西通信》行业深度:Wi-Fi6同步5G启航,共享万物互
2026-05-18栏目: 教程
-
不用纠结NSA与SA网络!对于5G手机来说,体验基本一致
2026-05-18栏目: 教程
-
你对自己的网站拥有所有权吗?
2026-05-18栏目: 教程
