In: Computer Science
The purpose of this lab is to become familiar with searching, inserting and deleting elements in a linked list.using java
public boolean contains(String name) // returns true if provided name exists in the list, otherwise returns false public void add(String name) // adds name to the list in its proper lexographical (alphabetical) ordering public void delete(String name) // removes name from list
public boolean contains(String name) {
Node temp = this.head;
while (temp != null) {
if (temp.data.compareTo(name) == 0) {
return true;
}
temp = temp.next;
}
return false;
}
public void add(String name) {
// if list is empty add directly
if (this.head == null) {
Node nn = new Node();
this.head = nn;
}
// else insert in alphabetical order
else {
// dummy node used for searching position where the node should be inserted
Node dummy = new Node();
Node current = dummy;
dummy.next = this.head;
// iterate until correct position is found
while (current.next != null && current.next.data.compareTo(name) < 0) {
current = current.next;
}
// insert node
Node nn = new Node();
nn.next = current.next;
current.next = nn;
}
}
public void delete(String name) {
Node temp = this.head;
while (temp != null) {
if (temp.data.compareTo(name) == 0) {
// search for prev node
Node prev = prev(name);
// remove the current node
prev.next = temp.next;
}
temp = temp.next;
}
}
private Node prev(String name) {
Node temp = this.head;
while (temp != null) {
if (temp.next.data.compareTo(name) == 0) {
return temp;
}
temp = temp.next;
}
return null;
}
Since the linkedlist structure was not specified clearly , standard definition is used to complete the code.Feel free to comment in case of any doubts.