我再次需要Java的帮助...我有一个简单的自定义Node类: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。如果为true,我将递增一个称为的整数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方法的返回值中包含指令的情况下,我才能得到它。你们将如何实现方法?希望我已经清楚了。非常感谢你
1 回答
萧十郎
TA贡献1815条经验 获得超13个赞
考虑以下代码行:
while(p != null){
...
}
return ... || p == null;
显然,这总是将返回true,因为在循环退出时p始终为null。
我建议您用两种方法来实现逻辑。第一个检查节点或其后继节点是否包含元素。第二个检查与第二个节点的所有元素。
boolean hasElement(int elem) {
return this.elem == elem || (next != null && next.hasElement(elem));
}
boolean hasAllElements(Node node1, Node node2) {
return node2.hasElement(node1.elem) && (next == null || hasAllElements(next, node2));
}
添加回答
举报
0/150
提交
取消