Java: Given two sets, LinkedSet this and LinkedSet that, consisting of a generic type of linked lists, write the method that returns the union of "this" and "that". You can use the LinkedSet constructor to construct a new LinkedSet that represents the union of the two.
public Set<E> union(Set<E> that) { }
private LinkedSet(LinkedNode head) {
this.head = head;
}
public class LinkedSet<T> implements Set<T> { /* * inner class to represent node */ private class LinkedNode { private T data; private LinkedNode next; public LinkedNode(T item) { data = item; next = null; } } private LinkedNode head; private int size; /* * adds item to bag if not already present * returns true if item successfully added, false if not */ public boolean add(T item) { // to keep the last element LinkedNode prev = null; LinkedNode start = head; while (start != null) { if (start.data.equals(item)) { return false; } prev = start; start = start.next; } if (head == null) { head = new LinkedNode(item); } else { prev.next = new LinkedNode(item); } size++; return true; } /* * removes item from set * returns removed item */ public T remove() { if (size == 0) { return null; } T removed = head.data; head = head.next; size--; return removed; } /* * returns item from set */ public T get() { if (size == 0) { return null; } return head.data; } /* * returns true if item is in set, false otherwise */ public boolean contains(T item) { LinkedNode current = head; for (int i = 0; i < size; i++) { if (current.data.equals(item)) { return true; } current = current.next; } return false; } public Set<T> union(Set<T> that) { LinkedSet<T> result = new LinkedSet<>(); LinkedNode l1 = head; while(l1 != null) { result.add(l1.data); l1 = l1.next; } LinkedNode l2 = head; while(l2 != null) { if(!result.contains(l2.data)) result.add(l2.data); l2 = l2.next; } return result; } /* * returns size of set */ public int size() { return size; } /* * returns string representation of contents of set */ public String toString() { if (size == 0) { return "[ ]"; } String s = "["; LinkedNode current = head; while (current.next != null) { s += current.data + ", "; current = current.next; } return s + current.data + "]"; } /* * checks if item is null and throws exception if so */ private void checkForNull(T item) { if (item == null) { throw new IllegalArgumentException("null not a possible value!"); } } }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.
Get Answers For Free
Most questions answered within 1 hours.