检查 LinkedList 是否包含数组的所有元素
Check that a LinkedList contains all the elements of an array
我想写一个方法public boolean containsArray(int[] arr)
,其中returns true
如果所有 数组的元素都在列表中,否则它 returns false
。
我想只使用下面的LinkedList
class。
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;
}
我的想法是在将列表值与数组元素进行比较的同时遍历列表,但我不确定如何正确地实现它。
你应该从另一个方向来处理这个问题。首先遍历数组的每个值,对于每个值在链表中查找。
此外,您的while
条件也不完全正确:例如,如果head
为空,while条件将触发异常。当 tmp
为空时,您应该退出循环,而不是当 tmp.next
为空时。
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;
}
我想写一个方法public boolean containsArray(int[] arr)
,其中returns true
如果所有 数组的元素都在列表中,否则它 returns false
。
我想只使用下面的LinkedList
class。
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;
}
我的想法是在将列表值与数组元素进行比较的同时遍历列表,但我不确定如何正确地实现它。
你应该从另一个方向来处理这个问题。首先遍历数组的每个值,对于每个值在链表中查找。
此外,您的while
条件也不完全正确:例如,如果head
为空,while条件将触发异常。当 tmp
为空时,您应该退出循环,而不是当 tmp.next
为空时。
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;
}