* inverse * returns the inverse of this symbol table. * the inverse is a symbol
ID: 3752439 • Letter: #
Question
* inverse
* returns the inverse of this symbol table.
* the inverse is a symbol table where the roles of the Keys and Values are switched
* Example:
* Consider the symbol table below, written as a collection of key value pairs
* A, 1
* B, 2
* C, 3
* The inverse this would be:
* 1, A
* 2, B
* 3, C
* In the original table, keys were Strings, values were Integers
* So in the inverse table, keys would be Integers and values would be Strings
* Note that the return type for the function is already correctly specified.
* That is: the invoking instance will be a Symbol table with key type: Key and value type: Value
* the inverse will be a symbol table with key type: Value and value type: Key
* Note: if the symbol table contains duplicate values,
* you may use any of the corresponding keys for the inverse
* Example:
* A, 1
* B, 2
* C, 3
* D, 2
* 2 will become a Key in the inverse symbol table and its value could be either B or D
*/
public LinkedListST<Value, Key> inverse() {
Explanation / Answer
Assuming that you have basic getters and setters inside LinkedListST class, the implementation will be something like this. Make sure that your class LinkedListST is declared as :-
public class LinkedListST<Key extends Comparable<Key>, Value extends Comparable<Value> >
This is really necessary to avoid out of bound error. This is done because we need the Key to be Comparable. Also the value is used as key, thus it also requires to be comparable.
public LinkedListST<Value, Key> inverse()
{
LinkedListST<Value, Key> inversest = new LinkedListST<Value, Key>();
// Iterating over the Symbol Table
for(Node n = this.first; n != null; n = n.next)
{
// If that value is not present in the inverse symbol table, add it.
if(inversest.get(n.val) == null)
{
inversest.put(n.val, n.key);
// System.out.println(n.val + " " + n.key);
}
}
return inversest;
}
Please rate positive if satisfied!!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.