如何将链表的一部分复制到另一个链表中?

How to copy a part of LinkedList into another LinkedList?

我有两个链表。我需要将第一个列表中的一部分(从索引 x 开始到索引 y 结束)复制到第二个列表。有什么方法可以做到这一点?

您可以使用 List.<b>addAll</b> and List.<b>subList</b>:

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> a = new LinkedList<>(Arrays.asList("A", "B", "C", "D"));
        System.out.printf("a = %s%n", a);
        List<String> b = new LinkedList<>(Arrays.asList("1", "2", "3", "4"));
        System.out.printf("b = %s%n", b);
        int x = 1;
        System.out.printf("x = %d%n", x);
        int y = 2;
        System.out.printf("y = %d%n", y);
        b.addAll(a.subList(x, y + 1));
        System.out.printf("b = %s%n", b);
    }
}

输出:

a = [A, B, C, D]
b = [1, 2, 3, 4]
x = 1
y = 2
b = [1, 2, 3, 4, B, C]
One addition to Sash Sinha answer, we can add the sublist at any index using b.addAll(0, a.subList(1, 3)).


    
List<String> a = new LinkedList<>(Arrays.asList("A", "B", "C", "D"));
        List<String> b = new LinkedList<>(Arrays.asList("1", "2", "3", "4"));
        b.addAll(0, a.subList(1, 3));
        System.out.println(b);

output:

[B, C, 1, 2, 3, 4]