【发布时间】:2018-12-02 05:06:08
【问题描述】:
我再次需要 Java 方面的帮助... 我有这个简单的自定义节点类:
class Node{
private int elem;
private Node next;
public Node(int elem, Node next){
this.elem = elem;
this.next = next;
}
public int getElem(){
return elem;
}
public void setElem(int elem){
this.elem = elem;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next = next;
}
}
我需要实现一个静态布尔方法,该方法将两个节点作为参数,如果第一个节点的所有元素都包含在第二个节点中,则返回 true。 示例输出:
1) Node p {5} Node q {5,5} returns true since element 5 of Node p is also in Node q
2) Node p {1,3,5} Node q {0,1,2,3,4,5} returns true since
all elements of Node p are also in Node q
3) Node p {5,3} Node q {3,4,6} returns false because
element 5 of Node p is not in Node q
4) If first Node given as parameter to method is empty
(with no values), the method will return true.
这是我的想法:
public static boolean included(Node p, Node q){
//every element in p is in q?
int count = 0;
int temp = 0;
int length = 0;
while(p != null){
temp = p.getElem();
length++;
while(q != null){
if(q.getElem() == temp)
count++;
q = q.getNext();
}
p = p.getNext();
}
return length == count || p == null;
}
对于Node p 的每个元素,我必须检查是否也在Node q 中。如果为真,我增加一个我称为count 的整数,否则我什么也不做。
对所有 p 元素完成此检查后,我会检查 count == size of Node p
或Node p is empty aka null
问题是:这个方法总是返回true。
我试图从返回值中删除 p == null 并且发生了一些变化,所以我怀疑这是问题所在,所以我向您展示了我是如何创建节点的:
Node p = null;
Node q = null;
int arr1[] = {5,4,3,2,1,0};
int arr2[] = {5,3,1};
for(int i = 0; i < arr1.length; i++)
p = new Node(arr1[i], p);
for(int i = 0; i < arr2.length; i++)
q = new Node(arr2[i], q);
有了这些节点,我应该得到true,但我只有在方法的返回值中包含指令p == null 时才能得到它。
你们将如何实现方法? 希望我已经清楚了。 非常感谢
【问题讨论】:
-
那是......实现
List的一种奇怪方式。通常情况下,不会直接对Nodes 进行操作,而是在列表上执行一些public boolean containsAll(List that)来实现此功能