https://leetcode-cn.com/problems/merge-two-sorted-lists/description/
感觉没有头节点的链表使用起来很麻烦:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode l3 = new ListNode(l1.val);
l3=l1.val<=l2.val?l1:l2;
ListNode res =l3;
if(l1.val<=l2.val)l1=l1.next;
else l2=l2.next;
while(l1!=null&&l2!=null) {
if(l1.val<=l2.val){
l3.next=l1;
l3=l1;
l1=l1.next;
}
else {
l3.next=l2;
l3=l2;
l2=l2.next;
}
}
if(l1==l2)
return res;
if(l1==null)
l3.next=l2;
else
l3.next=l1;
return res;
}
public static void main(String[] args) {
ListNode l1= new ListNode(1);
ListNode ll1 = l1;
l1.next = new ListNode(2);
l1.next = new ListNode(4);
ListNode l2= new ListNode(1);
ListNode ll2 = l2;
l2.next = new ListNode(3);
l2.next = new ListNode(4);
mergeTwoLists(ll1,ll2);
}
}
提交记录中,耗费时间最短的是递归算法:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode head = null;
if (l1.val <= l2.val){
head = l1;
head.next = mergeTwoLists(l1.next, l2);
} else {
head = l2;
head.next = mergeTwoLists(l1.next, l2);
}
return head;
}
}