21. Merge Two Sorted Lists (Easy)

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

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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Solutions

class Solution {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode ptr = head;

        ListNode p = l1;
        ListNode q = l2;

        while (p != null || q != null) {
            if (p != null && q != null) {
                if (p.val < q.val) {
                    ptr.next = p;
                    p = p.next;
                } else {
                    ptr.next = q;
                    q = q.next;
                }
            } else if (p == null) {
                ptr.next = q;
                q = q.next;
            } else { // if this conditional statement get hit, q is null
                ptr.next = p;
                p = p.next;
            }

            ptr = ptr.next;
        }

        return head.next;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-02-27 00:20:20

results matching ""

    No results matching ""