检查 LinkedList 是否包含数组的所有元素

时间:2021-03-23 16:13:56

标签: java arrays linked-list iteration

我想编写一个方法public boolean containsArray(int[] arr),如果所有数组的元素都在列表中,它返回true,否则返回false。 我想使用下面的 LinkedList 类。

public class LinkedList {
    public Node head = null;

    public class Node {
        public int value;
        public Node next;

        Node(int value, Node next) {
            this.value = value
            this.next = next;
        }
    }
}

到目前为止,这是我拥有的代码:

public boolean containsArray(int[] arr) {
    Node tmp = head;

    while(tmp.next != null) {
        for(int i = 0; i < arr.length; i++) {
            if(tmp.value == arr[i] {
                tmp = tmp.next;
            } else {
                return false;
            }
        }
    }
    return true;
}

我的想法是在将列表值与数组元素进行比较的同时遍历列表,但我不确定如何正确实现。

1 个答案:

答案 0 :(得分:1)

你应该从另一个方向解决这个问题。首先迭代数组中的每个值,并针对每个值在链表中查找。

此外,您的 while 条件并不完全正确:例如,如果 head 为 null,则 while 条件将触发异常。您应该在 tmp 为 null 时退出循环,而不是在 tmp.next 为 null 时退出。

public boolean containsArray(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        int value = arr[i];
        Node tmp = head;
        while (true) {
            if (tmp == null) {
                return false;
            }
            if (tmp.value == value) {
                break;
            }
            tmp = tmp.next;
        }
    }
    return true;
}