LintCode - 合并两个排序链表(普通)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:容易
要求:

将两个排序链表合并为一个新的排序链表

样例

给出 1->3->8->11->15->null,2->null, 返回1->2->3->8->11->15->null。

思路

/**
     * @param ListNode l1 is the head of the linked list
     * @param ListNode l2 is the head of the linked list
     * @return: ListNode head of linked list
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null){
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        
        ListNode result = new ListNode(0);
        ListNode tmp = result;
        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                tmp.next = l1;
                l1 = l1.next;
            }else if(l1.val > l2.val){
                tmp.next = l2;
                l2 = l2.next;
            }else{
                tmp.next = l1;
                l1 = l1.next;
                tmp = tmp.next;
                tmp.next = l2;
                l2 = l2.next;
            }
            tmp = tmp.next;
        }
        
        if(l1 != null){
            tmp.next = l1;
        }
        if(l2 != null){
            tmp.next = l2;
        }
        return result.next;
    }

你可能感兴趣的:(LintCode - 合并两个排序链表(普通))