Problem:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Explanation:
给定两个有序链表,合并成一条有序链表。
My Thinking:
使用两个指针分别遍历l1和l2,比较当前的两个数,将小的加入新的链表,当一方结束遍历时,将另一方的剩余结点加入新链表,时间复杂度为O(n),n为两个链表中元素个数较小的那个。
My Solution:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode mergedlist=new ListNode(-1);//创建一个新链表
ListNode currentnode=mergedlist;//创建新链表的移动指针
while(l1!=null && l2!=null){//当两个列表当前指针指向元素都不为空时,进行比较
if(l1.val>l2.val){
currentnode.next=l2;
l2=l2.next;
}else{
currentnode.next=l1;
l1=l1.next;
}
currentnode=currentnode.next;
}
if(l1==null){//将多余元素添加到链表后面
currentnode.next=l2;
}else{
currentnode.next=l1;
}
return mergedlist.next;
}
}
Optimum Thinking:
使用递归,每次比较两个数后,取出该数,将剩余两个链表的数继续比较,时间复杂度为O(n),因为要递归n步,n为两个链表中元素个数较小的那个。
Optimum 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;
}
}