Wednesday, March 7, 2018

[2018-Interview] Merge Two Sorted Lists

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

My answer: pretty simple and straightforward.



/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        }

        ListNode head = new ListNode(-1);        
        ListNode current = head;

        while(l1 != null && l2 != null) {
            if (l1.val > l2.val) {
                current.next = l2;
                l2 = l2.next;
            } else {
                current.next = l1;
                l1 = l1.next;
            }
            current = current.next;
        }
        ListNode remainingNode = l1 == null? l2 : l1;
        current.next = remainingNode;
        return head.next;
    }
}

No comments:

Post a Comment