Sunday, November 24, 2013

Merge two sorted list LeetCode

这个题主要考实现,没太多难度,两个linkedlist里面比head的值得大小,逐个接到新的LinkedList里面。设置一个dummy node。


public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(l1==null) return l2;
        if(l2==null) return l1;
        ListNode prev = new ListNode(-1);
        ListNode curr = prev;
        while(l1!=null && l2!=null){
            if(l1.val < l2.val){
                curr.next = l1;
                l1 = l1.next;
            }else{
                curr.next = l2;
                l2 = l2.next;
            }
            curr = curr.next;
        }
        if(l1 != null){
            curr.next = l1;
        }
        if(l2 != null){
            curr.next = l2;
        }
        return prev.next;
    }

No comments:

Post a Comment