I have written java code implementing Linked Lists from scratch. The problem is
ID: 3571553 • Letter: I
Question
I have written java code implementing Linked Lists from scratch. The problem is I don't know how to delete the instance of Student object from the list. Even though it works with String and Int.
Output:
John 1738 87 W. Wall St. Livonia, MI 48150
James 1738 87 W. Wall St. Livonia, MI 48150
After deletion:
John 1738 87 W. Wall St. Livonia, MI 48150
James 1738 87 W. Wall St. Livonia, MI 48150
Expected Output:
John 1738 87 W. Wall St. Livonia, MI 48150
James 1738 87 W. Wall St. Livonia, MI 48150
After deletion:
John 1738 87 W. Wall St. Livonia, MI 48150
There's my code. Thanks.
Explanation / Answer
class linkedlists {
public static void main(String [] args){
StudentList class1 = new StudentList();
class1.add(new Student("John", "1738", "87 W. Wall St. Livonia, MI 48150"));
class1.add(new Student("James", "1738", "87 W. Wall St. Livonia, MI 48150"));
System.out.println(class1);
class1.delete(new Student("James", "1738", "87 W. Wall St. Livonia, MI 48150"));
System.out.println("After deletion: ");
System.out.println(class1);
}
public static class StudentList{
private StudentNode list;
public StudentList(){
list = null;
}
public void add(Student s){
StudentNode node = new StudentNode(s);
StudentNode current = null;
if(list == null)
list = node;
else{
current = list;
while(current.next != null)
current = current.next;
current.next = node;
}
}
public String toString(){
String result = "";
StudentNode current = list;
if(current != null){
result = String.valueOf(current.value);
while(current.next != null){
current = current.next;
result += String.valueOf(current.value);
}
}
return result;
}
private class StudentNode{
public Student value;
public StudentNode next;
public StudentNode(Student value){
this.value = value;
next = null;
}
}
public boolean delete(Student n) {
StudentNode current = list;
StudentNode previous = null;
if(current == null)
return false;
while (current != null){ //loop should run until there is element in the list. no till next.
if (n.equals(current.value)){
if(previous != null)
previous.next = current.next;
else
list = current.next;
return true;
}
previous = current;
current = current.next;
}
return false;
}
}
public static class Student{
private String name, id, address;
public Student(String name, String id, String address){
this.name = name;
this.id = id;
this.address = address;
}
public String toString(){
String result;
result = name + " " + id + " " + address + " ";
return result;
}
public boolean equals(Student t){ //comparison by string
return this.toString().equals(t.toString());
}
}
}