链表-面试题25. 合并两个排序的链表
程序员文章站
2024-03-18 09:46:34
...
解题思路:迭代
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
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;
}
cur.next=l1==null?l2:l1;
return dummy.next;
}
}
解题思路二:递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
if(l1.val<=l2.val){
l1.next=mergeTwoLists(l1.next,l2);
return l1;
}
else{
l2.next=mergeTwoLists(l1,l2.next);
return l2;
}
}
}
参考博客链接:
上一篇: 【算法题】剑指offer之二叉树--python实现
下一篇: 算法刷题5【剑指offer系列之树】