[leetcode-排序]--21. Merge Two Sorted Lists

Question 21. Merge Two Sorted Lists

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.

中文:合并两个有序的链表,然后返回新的链表。新的链表应该是拼接的前面两个链表。

链表结点的定义:

//结点:
public class ListNode {
    public int val;
    public ListNode next;
    ListNode(int x) { val = x; }
}

实现思路:
1)判断l1和l2是否存在空链表,有空链表就可以直接返回。

2)找出l1和l2中最小的结点,作为新链表的表头结点。

3)然后依次比较遍历l1和l2,将较小的结点插入在新链表的后面。

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if (l1 == null ){
        return l2;
    }

    if(l2 == null){
        return l1;
    }

    if(l1==null && l2 == null){
        return null;
    }

    /** l1和l2均非空 */
    ListNode p1 = l1;
    ListNode p2 = l2;
    //先找出l1和l2的头结点中 较小的结点作为新链表的head
    ListNode head=null;
    if(l1.val<l2.val){
        head = l1;
        p1 = p1.next;
    }else {
        head = l2;
        p2 = p2.next;
    }
    //新链表的p指针
    ListNode p = head;

    //当p1和p2都不为空时
    while (p1!=null && p2 !=null){
        if(p1.val < p2.val){
            p.next = p1;
            p = p.next;
            p1 = p1.next;
        } else {
            p.next = p2;
            p = p.next;
            p2 = p2.next;
        }
    }

    if(p1 == null && p2 == null){
        return head;
    }else if(p1 == null && p2 != null){
        p.next = p2;
    }else if(p2 == null && p1 != null){
        p.next = p1;
    }

    return head;
}

一次Accept。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值