I am trying to write a boolean method isSubset (returns a boolean value if every element in set A is in set B and false otherwise) where method call can be written like this setA.subsetOf(setB). My thought is to extract each element of setA and compare it with setB. If the first element of setA is matched with any in setB, proceeding to next element in setA to check. If all elements in setA is matched with any element from setB, method returns true, else (not all elements from setA is in setB) returns false. I already wrote the method to check for containment of an element to a linked list as followed:
public boolean contain (Object target) {
boolean status = false;
Node cursor;
for (cursor = head; cursor.getNext() != null; cursor = cursor.getNext()) {
if (target.equals(cursor.getElement()))
status = true;
}
return status;
}
Since im still confused about the syntax of linked list operation, my question is how to extract each element and do the rest. Any help would be appreciated.
Node is declared
public Node(Object o, Node n) {
element = o;
next = n;
}
SLinkedList
public SLinkedList() {
head = new Node(null, null); // create a dummy head
size = 0;
}
First, your contain method has a small bug in it. The for condition
cursor.getNext() != null;should becursor != null;. Doing so prevents the search of empty sets (which would cause your code to crash) as well as allowing the last Node in the list to be searched. Your code would run faster if you didreturn status;afterstatus=true;The structure for isSubset would be very similar to the loop you created; the loop would look like this: