Sword Point offer mergeorderedlist merge two sorted list

Source: Internet
Author: User

Title Description:

Enter two incrementally sorted lists, merge the two linked lists, and make the nodes in the new list still in ascending order

Ideas:
Recursively scan two arrays each time you point the next pointer to a smaller value for the current node in the linked list

public static ListNode mergeorderedlist (ListNode list1, ListNode list2) {
        if (List1 = = null) {
            return list2;
        }
        if (list2==null) {
            return list1;
        }
        ListNode node;
        if (List1.data < list2.data) {
            node = List1;
            Node.next = Mergeorderedlist (List1.next, List2);
        } else {
            node = list2;
            Node.next = Mergeorderedlist (List1, List2.next);
        }
        return node;
    }
public class Mergeorderedlisttest extends Basetest {private ListNode list1;

    Private ListNode List2;
        @Override @Before public void SetUp () throws Exception {Super.setup ();
        int[] data1 = new Int[]{1, 2, 3, 4, 5};
        int[] data2 = new int[]{2, 3, 4, 7, 8};
        List1 = Initlist (data1);
    List2 = Initlist (data2); } @Test public void Test () throws Exception {ListNode ListNode = mergeorderedlist.mergeorderedlist (list1
        , List2);
    Printlist (ListNode);
        } private ListNode Initlist (int[] data) {listnode[] node = new Listnode[data.length];
        for (int i = 0; i < node.length; i++) {Node[i] = new ListNode (Data[i]);
        } for (int i = 0; i < node.length-1; i++) {node[i].next = node[i + 1];
    } return node[0]; 
    } private void Printlist (ListNode node) {while (node! = null) {System.out.print (node.data+ "");        node = Node.next; }
    }
}

Output results

1 2 2 3 3 4 4 5 7 8

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.