Im trying to write the methods to “union” which can be described: if A, B, C are sets, has the form C = A.union(B). Union returns a Set that contains all the elements in set A and B, but only list duplicates once.
My idea for this method is to traverse set A and add all of its elements to the union set, then traverse set B, if an element of set B is already present in the union set, then do not insert it to result, otherwise insert all to the union set.
This is complicated for a beginner like me since I want to include all 3 lists into the method (which I get a bunch of errors). I already wrote some methods in my SLinkedList class to check and add element but the parameters take an object from a Node
/** Singly linked list .*/
public class SLinkedList {
protected Node head; // head node of the list
protected int size; // number of nodes in the list
/** Default constructor that creates an empty list */
public SLinkedList() {
head = new Node(null, null); // create a dummy head
size = 0;
// add last
public void addLast(Object data) {
Node cur = head;
// find last node
while (cur.getNext() != null) {
cur = cur.getNext();
}
// cur refers to the last node
cur.setNext(new Node(data, null));
size++;
}
// contain method to check existing elements
public boolean contain (Object target) {
boolean status = false;
Node cursor;
for (cursor = head; cursor != null; cursor = cursor.getNext()) {
if (target.equals(cursor.getElement())) {
status = true;
}
}
return status;
}
public SLinkedList union (SLinkedList secondSet) {
SLinkedList unionSet = new SLinkedList();
secondSet = new SLinkedList();
Node cursor;
for(cursor = head.getNext(); cursor != null; cursor = cursor.getNext()) {
unionSet.addLast(cursor.getElement());
// traverse secondSet, if an element is existed in either set A or union
// set, skip, else add to union set
}
}
return unionSet;
}
}
Node class
/** Node of a singly linked list of strings. */
public class Node {
private Object element; // we assume elements are character strings
private Node next;
/** Creates a node with the given element and next node. */
public Node(Object o, Node n) {
element = o;
next = n;
}
/** Returns the element of this node. */
public Object getElement() { return element; }
/** Returns the next node of this node. */
public Node getNext() { return next; }
// Modifier methods:
/** Sets the element of this node. */
public void setElement(Object newElem) { element = newElem; }
/** Sets the next node of this node. */
public void setNext(Node newNext) { next = newNext; }
}
*update*
The question is if there is a second list involved public SLinkedList union (SLinkedList secondSet) , what syntax should i use to traverse set B and check if an element of set B is already present in result then do not insert it to result, otherwise insert. Do I need to creat a node for set B and traverse it?, there may be a compare method to compare the 2 sets outside of the union method?
Please help. Thanks all.
1 Answer