Leetcode 英語で説明する③(Java)



お題

https://leetcode.com/problems/merge-two-sorted-lists/description/

1. アルゴリズムの説明

The issue is to merge two given list in sorted.
To solve this, we'll compare the values of list1 and list2. Whichever smaller, we'll add the ListNode into the result.
Once List1 or List2 become null, we'll add the remaining not-null list to the result.

2. コード

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode res = new ListNode();
        if(list1 == null && list2 == null){
            return list1;
        }else if (list1 == null){
            return list2;
        }else if (list2 == null){
            return list1;
        }
        if(list1.val >= list2.val){
            res = list2;
            list2 = list2.next;
        }else{
            res = list1;
            list1 = list1.next;
        }
        ListNode temp = res;
        while(list1 != null && list2 != null){
            if(list1.val >= list2.val){
                temp.next = list2;
                temp = temp.next;
                list2 = list2.next;
            }else{
                temp.next = list1;
                temp = temp.next;
                list1 = list1.next;
            }
        }
        if(list1 != null){
            temp.next = list1;
        }else if (list2 != null){
            temp.next = list2;
        }
        return res;
    }
}


この記事が気に入ったらサポートをしてみませんか?