Jianzhi offer brush question record 3 ascending linked list

Jianzhi offer record 3

☁️ Title description: Merge two ascending linked lists into a new ascending linked list and return. The new linked list is formed by splicing all the nodes of the given two linked lists.

☁️ Example 1:

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

☁️ Example 2:

输入:l1 = [], l2 = []
输出:[]

☁️ Example 3:

输入:l1 = [], l2 = [0]
输出:[0]

☁️ Tips:

  • The range of the number of nodes of the two linked lists is[0, 50]
  • -100 <= Node.val <= 100
  • l1and l2are in non-decreasing order

☁️ Method 1: Recursion

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

insert image description here

☁️ Method 2: Iteration

/**
 * 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(list1==null){
    
    
            return list2;
        }
        else if(list2==null){
    
    
            return list1;
        }
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        while(list1 != null && list2 != null){
    
    
            if(list1.val<list2.val){
    
    
                cur.next = list1;
                list1 = list1.next;
            }else{
    
    
                cur.next = list2;
                list2 = list2.next;
            }
            cur =cur.next;

        }
        if(list1 != null){
    
    
            cur.next=list1;
        }else if(list2 != null){
    
    
            cur.next=list2;
        }
        return head.next;
    }
}

insert image description here

Guess you like

Origin blog.csdn.net/m0_60266328/article/details/125673263