合并两个升序链表

2020-05-29  本文已影响0人  cbhe
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        if (l1 == null){
            return l2;
        }
        if (l2 == null){
            return l1;
        }

        ListNode ret = new ListNode(0);
        ListNode p = ret;

        for (;l1!= null && l2 != null;){
            if (l1.val<l2.val){
                p.next = l1;
                l1 = l1.next;
            } else {
                p.next = l2;
                l2 = l2.next;
            }

            p = p.next;
            p.next = null;
        }
        
        if (l1 == null){
            p.next = l2;
        }
        if (l2 == null){
            p.next = l1;
        }
        
        return ret.next;
    }
}
上一篇下一篇

猜你喜欢

热点阅读