103 lines
2.8 KiB
Java
103 lines
2.8 KiB
Java
/**
|
|
* Provides methods to manipulate the Trie. <br />
|
|
* The Trie only saves the root Node of which every Trie-Operation starts.
|
|
*/
|
|
public class Trie {
|
|
|
|
/**
|
|
* The root Node of the Trie.
|
|
*/
|
|
private Node root;
|
|
/**
|
|
* creates new Trie.
|
|
*/
|
|
public Trie() {
|
|
this.root = new Node();
|
|
}
|
|
|
|
/**
|
|
* adds new Student <code>key</code> with
|
|
* points <code>points</code> to the Trie.
|
|
* @param key Student to add
|
|
* @param points points of Student
|
|
* @return <code>true</code> if add was successful or <br />
|
|
* <code>false</code> if Student already exists
|
|
*/
|
|
public boolean add(String key, Integer points) {
|
|
Node iterator = this.root;
|
|
for (int i = 0; i < key.length(); i++) {
|
|
if (iterator.getChild(key.charAt(i)) == null) {
|
|
new Node(key.charAt(i), iterator);
|
|
}
|
|
iterator = iterator.getChild(key.charAt(i));
|
|
}
|
|
if (iterator.getPoints() == null) {
|
|
iterator.setPoints(points);
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* deletes Student <code>key</code> in the Trie.
|
|
* @param key Student to delete
|
|
* @return <code>true</code> if delete was successful or <br />
|
|
* <code>false></code> if Student does not exist
|
|
*/
|
|
public boolean delete(String key) {
|
|
Node hlp = this.root.find(key);
|
|
if (hlp == null) {
|
|
return false;
|
|
}
|
|
if (hlp.getPoints() != null) {
|
|
hlp.deleteMe();
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* changes points <code>points</code> of Student <code>key</code>
|
|
* in the Trie.
|
|
* @param key Student to change
|
|
* @param points points of Student to change
|
|
* @return <code>true</code> if change was successful or<br />
|
|
* <code>false</code> if Student does not exist
|
|
*/
|
|
public boolean change(String key, Integer points) {
|
|
Node hlp = this.root.find(key);
|
|
if (hlp == null) {
|
|
return false;
|
|
}
|
|
if (hlp.getPoints() != null) {
|
|
hlp.setPoints(points);
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Getter for points of Student <code>key</code> in the Trie.
|
|
* @param key Student to search for
|
|
* @return <code>points</code> of Student or<br />
|
|
* <code>null</code> if Student does not exist
|
|
*/
|
|
public Integer points(String key) {
|
|
Node hlp = this.root.find(key);
|
|
if (hlp != null) {
|
|
return hlp.getPoints();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Method to print the hole Trie.
|
|
* @return <code>string</code> of the Trie in the requested format
|
|
*/
|
|
public String toString() {
|
|
return this.root.toString();
|
|
}
|
|
} |