Merge two lists in constant time in Java

前端 未结 4 1712
再見小時候
再見小時候 2020-12-11 01:35

Does anyone know if it\'s possible to merge two lists (or any collection) in constant time in Java ?

http://www.cppreference.com/wiki/stl/list/splice

It\'s s

4条回答
  •  借酒劲吻你
    2020-12-11 02:18

    You could do the next steps: get the LinkedList of Java source here: LinkedList.java

    Then over this implementation add the next function:

    public void concatenate(LinkedList list)
    {   
        header.previous.next = list.header.next;
        list.header.next.previous = header.previous;
        list.header.previous.next = header.next;
        header.next.previous = list.header.previous; 
        list.header.next = header.next;
        header.previous = list.header.previous;
    
        size = size + list.size;
        modCount = modCount + list.modCount + 1;
        list.size = size;
        list.modCount = modCount;
    }
    

    With this code, the 2 LinkedList will be the same LinkedList, so you'll merge in one. The container LinkedList will add the param LinkedList at the end and finally the header of both LinkedList will point to the first and last element. In this method I dont care about if one of the two list is empty so make sure you have the two list with elements before use it or you'll have to check and take care about this.

    Test1:

    public static void main(String[] args)
    {
        LinkedList test1 = new LinkedList();
        LinkedList test2 = new LinkedList();
        test1.add("s1");
        test1.add("s2");
        test2.add("s4");
        test2.add("s5");
        test1.concatenate(test2);
        System.out.println(test1);
        System.out.println(test2);
    }
    

    out:

    [s1, s2, s4, s5]
    [s1, s2, s4, s5]
    

    Test2 performance:

    public static void main(String[] args)
    {
        int count = 100000;
        myutil.LinkedList test1 = new myutil.LinkedListExt<>();
        myutil.LinkedList test2 = new myutil.LinkedListExt<>();
        test1.add("s1");
        test1.add("s2");
        test2.add("s3");
        test2.add("s4");
        for (int i=0; i test3 = new java.util.LinkedList<>();
        java.util.LinkedList test4 = new java.util.LinkedList<>();
        test3.add("s1");
        test3.add("s2");
        test4.add("s3");
        test4.add("s4");
        for (int i=0; i

    out:

    0.004016
    10.508312
    

提交回复
热议问题