代码改变世界

leetcode-0021 merge-two-sorted-lists

2022-05-07 09:02  jetwill  阅读(28)  评论(0编辑  收藏  举报

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

/**
 * 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 {
    /* apply the two-pointer technique */
    // public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
    //     if(list1 == null) return list2;
    //     if(list2 == null) return list1;
    //     ListNode resultNode = new ListNode();
    //     ListNode p = resultNode;
    //     while(list1 != null && list2 != null){
    //         if(list1.val < list2.val){
    //             p.next = list1;
    //             list1 = list1.next;
    //         }else{
    //             p.next = list2;
    //             list2 = list2.next;
    //         }
    //         p = p.next;
    //     }
    //     if(list1 != null){
    //         p.next = list1;
    //     }
    //     if(list2 != null){
    //         p.next = list2;
    //     }
    //     return resultNode.next;
    // }

    /* apply the recursion technique */
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;
        if(list1.val < list2.val){
            list1.next = mergeTwoLists(list1.next, list2);
            return list1;
        }
        list2.next = mergeTwoLists(list1, list2.next);
        return list2;
    }    
}

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-two-sorted-lists