Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

/**
 * 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) {
        ListNode fakehead = new ListNode(0);
        ListNode p = fakehead;
        ListNode p1 = l1;
        ListNode p2 = l2;

        while(p1 != null || p2 != null) {
            int n1 = Integer.MAX_VALUE;
            if(p1 != null)
                n1 = p1.val;

            int n2 = Integer.MAX_VALUE;
            if(p2 != null)
                n2 = p2.val;

            if(n1 < n2) {
                p.next = p1;
                p1 = p1.next;
            } else {
                p.next = p2;
                p2 = p2.next;
            }
            p = p.next;
        }

        return fakehead.next;
    }
}

results matching ""

    No results matching ""