美文网首页程序员
剑指offer----合并两个排序的链表

剑指offer----合并两个排序的链表

作者: qming_c | 来源:发表于2018-02-04 16:04 被阅读0次

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

    /*
    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 || list2 == null)
            {
                return list1 != null ? list1 : list2;
            }
            if(list1.val < list2.val){
                list1.next =  Merge(list1.next, list2);
                return list1;
            }else{
                list2.next =  Merge(list1, list2.next);
                return list2;
            }
        }
    }
    

    这是使用递归的方法,没层递归返回list1 与 list2中最小的节点, 并将next指针指向下一层递归,并将为排序的节点传入参数中。
    代码二

    public class Solution {
        public ListNode Merge(ListNode list1,ListNode list2) {
            if(list1 == null || list2 == null){
                return list1 == null ? list2 : list1;
            }
            ListNode head = null;
            ListNode current = null;
            if(list1.val <= list2.val){
                head = list1;
                current = list1;
                list1 = list1.next;
            }else{
                head = list2;
                current = list2;
                list2 = list2.next;
            }
            while(list1 != null && list2 != null){
                if(list1.val <= list2.val){
                    current.next = list1;
                    current = current.next;
                    list1 = list1.next;
                }else{
                    current.next = list2;
                    current = current.next;
                    list2 = list2.next;
                }
            }
            current.next = (list1 == null ? list2 : list1);
            return head;
        }
    }
    

    这是遍历版本,首先初始化current和head(head头结点,current用来构造排序之后的链表)通过比较不断的将节点加入到current。
    因为当list1, list2一方为null时循环就结束了,最后需要将非空一方的节点全部接到current的后面。

    相关文章

      网友评论

        本文标题:剑指offer----合并两个排序的链表

        本文链接:https://www.haomeiwen.com/subject/bgumzxtx.html