链表专题一合并有序链表

合并两个有序链表:

LeetCode21 将两个升序链表合并为一个新的升序链表并返回,新链表是通过拼接给定的两个链表的所有节点组成的。
一种是新建一个链表,然后分别遍历两个链表,每次都选最小的结点接到新链表上,最后排完。另外一个就是将一个链表结点拆下来,逐个合并到另外一个对应位置上去。这个过程本身就是链表插入和删除操作的拓展,难度不算大,这时候代码是否优美就比较重要了。

public  ListNode mergeTwoLists(ListNode list1, ListNode list2) {
    ListNode newHead = new ListNode(-1);
    ListNode res = newHead;
    while (list1 != null && list2 != null) { 

        if (list1.val < list2.val) {
            newHead.next = list1;
            list1 = list1.next;
        } else if (list1.val > list2.val) {
            newHead.next = list2;
            list2 = list2.next;
        } else { //相等的情况,分别接两个链
            newHead.next = list2;
            list2 = list2.next;
            newHead = newHead.next;
            newHead.next = list1;
            list1 = list1.next;
        }
        newHead = newHead.next;

    }
    //下面的两个while最多只有一个会执行
    while (list1 != null) {
        newHead.next = list1;
        list1 = list1.next;
        newHead = newHead.next;
    }
    while (list2 != null) {
        newHead.next = list2;
        list2 = list2.next;
        newHead = newHead.next;
    }

    return res.next;
}

对上面的进行优化
 

public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
    ListNode prehead = new ListNode(-1);
    ListNode prev = prehead;
    while (list1 != null && list2 != null) {
        if (list1.val <= list2.val) {
            prev.next = list1;
            list1 = list1.next;
        } else {
            prev.next = list2;
            list2 = list2.next;
        }
        prev = prev.next;
    }
    // 最多只有一个还未被合并完,直接接上去就行了,这是链表合并比数组合并方便的地方
    prev.next = list1 == null ? list2 : list1;
    return prehead.next;
}


合并K个链表:
两两合并

public ListNode mergeKLists(ListNode[] lists) {
    ListNode res = null;
    for (ListNode list: lists) {
        res = mergeTwoLists(res, list);
    }
    return res;
}


一道很无聊的好题:

 注意ab的开闭区间,并且设置ij寻找pre和post
 

public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
    ListNode pre1 = list1, post1 = list1, post2 = list2;
    int i = 0, j = 0;
    while(pre1 != null && post1 != null && j < b){
        if(i != a - 1){
            pre1 = pre1.next;
            i++;
        } 
        if(j != b){
            post1 = post1.next;
            j++;
        } 
    }
    post1 = post1.next;
    //寻找list2的尾节点
    while(post2.next != null){
        post2 = post2.next;
    }
    //链1尾接链2头,链2尾接链1后半部分的头
    pre1.next = list2;
    post2.next = post1;
    return list1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值