剑指offer题解——合并两个有序的链表Java

题解一

采用递归,每次取出两个链表中较小的一个节点,接下来Merge取后剩下的两个链表,一直到两个链表中有一个为空。

图解:
在这里插入图片描述
每次递归,让temp为两个链表中较小的节点,temp.next为下一次递归中较小的节点,每次递归返回temp给上一个节点。

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null) {
            return list2;
        }
        
        if(list2 == null) {
            return list1;
        }
        
        ListNode temp = null;
        if(list1 != null && list2 != null) {
            if(list1.val < list2.val) {
                temp = list1;
                list1.next = Merge(list1.next, list2);
            } else {
                temp = list2;
                list2.next = Merge(list1, list2.next);
            }
        }
        
        return temp;
    }
}

题解二

不用递归,定义一个新的链表,定义一个辅助指针temp来遍历新链表,注意要定义一个指针head来保存新链表的第一个节点,否则遍历到最后无法找到新链表的头部。用两个指针first和second分别遍历两个链表,每次取较小的节点作为新链表的下一个节点,较小节点的指针后移,直到两个链表中有一个为空。

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        
        if(list1 == null) {
            return list2;
        }
        
        if(list2 == null) {
            return list1;
        }
        
        ListNode first = list1;
        ListNode second = list2;
        ListNode temp = new ListNode(-1);
        ListNode head = temp;
        
        while(first != null && second != null) {
            if(first.val > second.val) {
                temp.next = second;
                second = second.next;
                temp = temp.next;
            } else {
                temp.next = first;
                first = first.next;
                temp = temp.next;
            }
        }
        
        if(first == null) {
            temp.next = second;
        }
        
        if(second == null) {
            temp.next = first;
        }
        
        return head.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值