合并两个排序链表

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

理解:

首先考虑特殊情况的出现。常规情况中,对list1和list2中的val进行对比。根据对比的情况,赋予newList,让newList的next**指向Merge递归的结果**,这样才能连接成链。
对于链表的题一定要确认链表中间没有丢失,最后要确认是否真的成链。

/*
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;
        }else if(list2 == null){
            return list1;
        }else if(list1==null && list2==null){
            return null;
        }
        ListNode newList = null;
        if(list1.val <= list2.val){
            newList = list1;
            newList.next = Merge(list1.next, list2); //递归
        }else{
            newList = list2;
            newList.next = Merge(list1, list2.next); //递归
        }
        return newList;
    }
}

知识点:
- 链表 ;
- 递归

猜你喜欢

转载自blog.csdn.net/RhythmWANG/article/details/81169990
今日推荐