简体   繁体   中英

Check that a LinkedList contains all the elements of an array

I would like to write a method public boolean containsArray(int[] arr) which returns true if all the elements of the array are in the list, otherwise it returns false . I would like to only use the LinkedList class below.

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;
        }
    }
}

So far this is the code I have:

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;
}

My idea is to iterate over the list while comparing the list values to the array elements but I am not sure how to implement this properly.

You should approach this in the other direction. First iterate each value of the array, and for each value look in the linked list to find it.

Also, your while condition is not entirely correct: for instance, if head is null, the while condition will trigger an exception. You should exit the loop when tmp is null, not yet when tmp.next is 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM