LinkedList——No.21 Merge two sorted lists

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;
		}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值