Tuesday, March 22, 2016

[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.
Subscribe to see which companies asked this question


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        
        ListNode resPreHead = new ListNode(0);
        
        ListNode index = resPreHead;
        
        while(null != l1 && null != l2){
            if(l1.val > l2.val){
                index.next = l2;
                l2 = l2.next;
            }else{
                index.next = l1;
                l1 = l1.next;
            }
            index = index.next;
            // be safe.
            index.next = null;
        }
        
        if (null == l1){
            index.next = l2;
        }else{
            index.next = l1;
        }
        
        return resPreHead.next;
    }
}

No comments:

Post a Comment