力扣题:合并两个有序链表(JAVA)

题目描述

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
力扣题:合并两个有序链表(JAVA)_第1张图片

解题代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
 //根据不同的情况传递归参数时不同
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (null==list1&&null==list2){
            return null;
        }
        if (null!=list1&&null==list2){
            return list1;
        }
        if (null==list1&&null!=list2){
            return list2;
        }
        if (null==list1.next&&null==list2.next){
            if (list2.val>=list1.val){
                return new ListNode(list1.val,list2);
            }else {
                return new ListNode(list2.val,list1);
            }
        }else if (null!=list1.next&&null==list2.next){
            if (list2.val>=list1.val){
                return new ListNode(list1.val,mergeTwoLists(list1.next,list2));
            }else {
                return new ListNode(list2.val,list1);
            }
        }else if (null==list1.next&&null!=list2.next){
            if (list2.val>=list1.val){
                return new ListNode(list1.val,list2);
            }else {
                return new ListNode(list2.val,mergeTwoLists(list1,list2.next));
            }
        }else {
            if (list2.val>=list1.val){
               return new ListNode(list1.val,mergeTwoLists(list1.next,list2));
            }else {
                return new ListNode(list2.val,mergeTwoLists(list1,list2.next));
            }
        }
    }
}

你可能感兴趣的:(链表,java,leetcode)