0

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.

asked Mar 23, 2021 at 16:13
1
  • 1
    Can you tag your question with the language you use? Commented Mar 23, 2021 at 18:17

1 Answer 1

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;
}
answered Mar 23, 2021 at 18:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.