Merge two Sorted Lists--Leetcode

Source: Internet
Author: User
Original title Link: http://oj.leetcode.com/problems/merge-two-sorted-lists/

This topic is relatively simple, classic linked list basic operation. Maintaining the two pointers corresponds to two linked lists, because it is generally based on a linked list, such as L1, then if the L1 of the element is relatively small, then move the L1 directly, otherwise L2 the current element into the L1 of the current element before. Algorithm time complexity is O (m+n), M and N are two linked list length, space complexity is O (1), the code is as follows:

Public ListNode mergetwolists (listnode L1, ListNode L2) {
    ListNode helper = new ListNode (0);
    ListNode pre = helper;
    Helper.next = L1;
    while (l1!=null && L2!= null)
    {
        if (l1.val>l2.val)
        {
            ListNode next = l2.next;
            L2.next = Pre.next;
            Pre.next = L2;
            L2 = Next;
        else
        {
            L1 = l1.next;
        }
        Pre = Pre.next;

    }
    if (l2!=null)
    {
        pre.next = L2;
    }
    return helper.next;
}
This problem is similar to the merge Sorted Array, except that the latter is a combined operation of an array, which may be asked together in an interview. Extended topic Merge K Sorted Lists, this is a more useful in the distributed system of basic operations, or need to pay attention to, interview can emit a lot of problems.

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.