合并两个排序的链表

2年前 (2022) 程序员胖胖胖虎阿
244 0 0

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则

这道题用到了分治法的思想:将一个难以直接解决的大问题,分割成一些规模较小的相同问题,以便各个击破,分而治之

主要思路是:两个指针分别指向两个链表,一开始是头结点,然后比较结点大小,哪个小则合并到第三个链表,并向前移动一个结点。如果一个链表已经遍历完成,而另一个链表还未遍历完成,则将未遍历完的剩余元素合并到第三个链表,最后返回第三个链表的首结点

解法一

普通的迭代版本

public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null) {
            return list2;
        }
        if(list2 == null) {
            return list1;
        }
        // 创建一个头结点,用于产生链表
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        while(list1 != null && list2 != null) {
            if(list1.val >= list2.val) {
            	// 将 list2 指向的结点链接到 cur 的 next 指针
                cur.next = list2;
                // list2 指向下一个结点
                list2 = list2.next;
            } else {
            	// 将 list1 指向的结点链接到 cur 的 next 指针
                cur.next = list1;
                // list1 指向下一个结点
                list1 = list1.next;
            }
            cur = cur.next;
        }
        // 将 list1 或者 list2 剩下的部分链接到 cur 的后面
        if(list1 == null) {
            cur.next = list2;
        } else if(list2 == null) {
            cur.next = list1;
        }
        return head.next;
    }
}

解法二

不创建头结点的方法

public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null) {
            return list2;
        }
        if(list2 == null) {
            return list1;
        }
        // 头结点指针
        ListNode head = null;
        ListNode cur = null;
        while(list1 != null && list2 != null) {
            if(list1.val >= list2.val) {
            	// 让头结点指向最小的元素
                if(head == null) {
                    head = cur = list2;
                } else {
                    cur.next = list2;
                    cur = cur.next;
                }
                list2 = list2.next;
            } else {
                if(head == null) {
                    head = cur = list1;
                } else {
                    cur.next = list1;
                    cur = cur.next;
                }
                list1 = list1.next;
            }
        }
        if(list1 == null) {
            cur.next = list2;
        } else if(list2 == null) {
            cur.next = list1;
        }
        return head;
    }
}

解法三

使用递归解法

public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }
        if(list1.val <= list2.val){
            list1.next = Merge(list1.next, list2);
            return list1;
        }else{
            list2.next = Merge(list1, list2.next);
            return list2;
        }        
    }
}

版权声明:程序员胖胖胖虎阿 发表于 2022年10月1日 上午5:00。
转载请注明:合并两个排序的链表 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...