[Leetcode] 21. Merge two Sorted Lists java__ merged

Source: Internet
Author: User
    /**21. Merge two Sorted Lists 
     * @param L1
     * @param L2
     * @return Merging two ordered lists/public
    ListNode mergetwolists (Li Stnode L1, ListNode L2) {
        listnode ret = new ListNode ( -1);
        ListNode L = ret;

        while (L1!= null && L2!= null) {
            if (L1.val < L2.val) {
                l.next = L1;
                L1 = L1.next;
            } else {
                l.next = L2;
                L2 = L2.next;
            }

        while (L1!= null) {
            l.next = L1;
            L1 = L1.next;
        }
        while (L2!= null) {
            l.next = L2;
            L2 = L2.next;
        }
        return ret.next;
    }

Improved: Linked list, so do not read each loop

 public ListNode mergetwolists (listnode L1, ListNode L2) {listnode ret = new ListNode
        (-1);
        ListNode rethead = ret;
        if (L1 = = NULL && L2 = null) {return null;
        }else if (L1 = null) {return L2;
        else if (L2 = null) {return L1; 
                while (L1!= null && L2!= null) {if (L1.val <= l2.val) {ret.next = L1;
                L1 = L1.next;
            ret = Ret.next;
                else {ret.next = L2;
                L2 = L2.next;
            ret = Ret.next;
        } if (L1!= null) {ret.next = L1;
        } if (L2!= null) {ret.next = L2;
    return rethead.next; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.