Need a java program that completes the following: Suppose the names \"Bob\", \"D
ID: 3668609 • Letter: N
Question
Need a java program that completes the following: Suppose the names "Bob", "Dan", and "Ben", are added, the result is: ----- ----- ----- ----- ----- head -->| B |-->| Ben |-->| Bob |-->| D |-->| Dan |-- ----- ----- ----- ----- ----- | --- - If the names "Deb" and "Sarah" are added, it looks like this: ----- ----- ----- ----- ----- ----- ----- ----- head -->| B |-->| Ben |-->| Bob |-->| D |-->| Dan |-->| Deb |--> | S |-->|Sarah|-- ----- ----- ----- ----- ----- ----- ----- ----- | --- - If "Deb" and "Sarah" are deleted, the list should look like the first list again. Details: Create a Java class called Index (not generic) that stores names and implements the structure shown above. Note that the names are kept in sorted order. Letter nodes are always uppercase. Lowercase names will follow uppercase strings in normal sorted order. You may *not* use Java's LinkedList class. You should create your own nodes and link them together as shown in the illustration. Your class should support the following methods. 20 points add - Adds a new string. Adds the letter node if not already present. 20 points remove - Removes a string. If the string is the last one for a letter, the letter node should also be removed. 20 points removeLetter - Removes a letter and all strings for that letter. 20 points find - Finds a string by traversing the nodes. 10 points toString - Prints the list as shown below using the first list above as an example: B Ben Bob D Dan 10 points main - Demonstrates the methods of your Index class
Explanation / Answer
public class Index{
public Node start;
public class Node{
String data;
Node link;
Node(String d){
data = d;
link = null;
}
}
Index(){
start = null;
}
void add(String s){
if(start == null){
start = new Node(s);
}
else{
Node temp = start;
while(temp.link != null && temp.link.data.compareTo(s) < 0){
temp = temp.link;
}
if(temp.link != null && temp.link.data.compareTo(s) == 0) return;
Node x = new Node(s);
x.link = temp.link;
if(temp.data.charAt(0) != s.charAt(0)){
Node n = new Node(s.charAt(0) + "");
temp.link = n;
temp = n;
}
temp.link = x;
}
}
public void remove(String s){
if(start.data.compareTo(s) == 0){
start = start.link;
return;
}
Node temp = start;
while(temp.link != null && temp.link.data.compareTo(s) != 0){
temp = temp.link;
}
if(temp.link == null) return;
temp.link = temp.link.link;
}
public void removeLetter(char l){
String letter = l + "";
Node temp = start;
while(temp.link != null){
if(temp.data.charAt(0) == l) temp.link = temp.link.link;
temp = temp.link;
}
}
public String toString(){
Node temp = start;
String string = "head";
while(temp != null){
string += " |-->| " + temp.data;
temp = temp.link;
}
return string;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.