문제

제출한 코드

/**
 * 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 l1, ListNode l2) {
        return getNextNode(l1, l2, new ListNode());
    }

    private ListNode getNextNode(ListNode l1, ListNode l2, ListNode currentNode) {
        if (l1 == null && l2 == null) {
            return null;
        }
        if (l1 == null) {
            currentNode = new ListNode(l2.val, getNextNode(null, l2.next, currentNode));
        } else if (l2 == null) {
            currentNode = new ListNode(l1.val, getNextNode(l1.next, null, currentNode));
        } else {
            if (l1.val > l2.val) {
                currentNode = new ListNode(l2.val, getNextNode(l1, l2.next, currentNode));
            } else {
                currentNode = new ListNode(l1.val, getNextNode(l1.next, l2, currentNode));
            }
        }
        return currentNode;
    }
}

잘한점

개선 할 점