Usted podría hacer los siguientes pasos: obtener la ListaEnlazada de fuente de Java aquí: LinkedList.java
Luego sobre esta implementación añadir la siguiente función:
public void concatenate(LinkedList<E> 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;
}
Con este código, el 2 LinkedList será la misma LinkedList, por lo que se fusionará en una. El contenedor LinkedList agregará param LinkedList al final y finalmente el encabezado de LinkedList apuntará al primer y último elemento. En este método, no me importa si una de las dos listas está vacía, así que asegúrese de tener las dos listas con los elementos antes de usarlo o tendrá que verificar y tener cuidado con esto.
Prueba1:
public static void main(String[] args)
{
LinkedList<String> test1 = new LinkedList<String>();
LinkedList<String> test2 = new LinkedList<String>();
test1.add("s1");
test1.add("s2");
test2.add("s4");
test2.add("s5");
test1.concatenate(test2);
System.out.println(test1);
System.out.println(test2);
}
a cabo:
[s1, s2, s4, s5]
[s1, s2, s4, s5]
Prueba2 rendimiento:
public static void main(String[] args)
{
int count = 100000;
myutil.LinkedList<String> test1 = new myutil.LinkedListExt<>();
myutil.LinkedList<String> test2 = new myutil.LinkedListExt<>();
test1.add("s1");
test1.add("s2");
test2.add("s3");
test2.add("s4");
for (int i=0; i<count; ++i)
test2.add("s");
long start = System.nanoTime();
test1.concatenate(test2);
long elapsedTime = System.nanoTime() - start;
System.out.println(elapsedTime/1000000.0);
java.util.LinkedList<String> test3 = new java.util.LinkedList<>();
java.util.LinkedList<String> test4 = new java.util.LinkedList<>();
test3.add("s1");
test3.add("s2");
test4.add("s3");
test4.add("s4");
for (int i=0; i<count; ++i)
test4.add("s");
start = System.nanoTime();
test3.addAll(test4);
elapsedTime = System.nanoTime() - start;
System.out.println(elapsedTime/1000000.0);
}
fuera:
0.004016
10.508312
muy agradable , Gracias. – Damien