I need some help with Java again... I have this simple custom Node class:
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;
}
}
I need to implement a static boolean method which takes two nodes as parameter and returns true if all elements of first Node are contained in second Node. Example Output:
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.
This is my idea:
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;
}
For every element of Node p i must check if is also in Node q. If true, I increment an integer I called count, else I do nothing.
Once this check is done on all p elements, I check if count == size of Node p
or Node p is empty aka null
Problem is: this method always returns true.
I tried to remove p == null from return value and something changed, so I suspect that's the issue so I show you how I create Nodes:
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);
With those Nodes I should get true, but I get it only where instruction p == null is included in return value of method.
How would you guys implement method? Hope I've been clear. Thank you very much
List. Normally, one would not operate on theNodes directly, but on the list and one would impelment somepublic boolean containsAll(List that)for this functionality