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.
-
1Can you tag your question with the language you use?trincot– trincot03/23/2021 18:17:58Commented Mar 23, 2021 at 18:17
1 Answer 1
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;
}