Clicky

Leetcode 21 "Merge Two Sorted Lists"

January 1, 0001

21. Merge Two Sorted Lists

Result

Runtime: 1 ms, faster than 81.82% of Java online submissions for Merge Two Sorted Lists.

Memory Usage: 43 MB, less than 55.19% of Java online submissions for Merge Two Sorted Lists.

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