Wednesday, January 7, 2015

LeetCode 21: 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.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode helper = new ListNode(0);
        ListNode node = helper;
        ListNode p1 = l1; // Point to l1
        ListNode p2 = l2; // Point to l2        

        while (p1 != null || p2 != null)
        {
            if (p1 == null)
            {
                node.next = p2;
                p2 = p2.next;
                node = node.next;
            }
            else if (p2 == null)
            {
                node.next = p1;
                p1 = p1.next;
                node = node.next;
            }
            else if (p1.val < p2.val)
            {
                node.next = p1;
                p1 = p1.next;
                node = node.next;
            }
            else
            {
                node.next = p2;
                p2 = p2.next;
                node = node.next;
            }
        }
        
        return helper.next;
    }
}

No comments:

Post a Comment