folks, the implementation of the LinkedList causes me a little of misunderstanding. I know how to implement all of the methods of the LinkedList but I do not understand why the class Link contains its own object inside itself (inside the class Link). Could smb please explain why class Link contains its own object inside it? Is there any analogy? Thanks in advance!
Class Link
package LinkedList;
public class Link {
public String data;
public Link next;
public Link(String data){
this.data = data;
this.next = null;
}
public void display(){
System.out.println(data);
}
}
Class `LinkedList`
class LinkedList{
public Link firstLink;
public LinkedList(){
this.firstLink = null;
}
public void insert(String data){
Link myLink = new Link(data);
myLink.next = firstLink;
firstLink = myLink;
}
public Link deleteFirst(){
Link deletedLink = firstLink;
firstLink = firstLink.next;
return deletedLink;
}
public boolean search(String data){
Link current = firstLink;
while(current != null){
if(current.data.equals(data)){
return true;
}
else{
current = current.next;
}
}
return false;
}
public void displayList(){
Link current = firstLink;
while(current != null){
current.display();
current = current.next;
}
}
}
Class LinkedTester
package LinkedList;
public class LinkTester {
public static void main(String[] args){
LinkedList theLinkedList = new LinkedList();
theLinkedList.insert("A");
theLinkedList.insert("B");
theLinkedList.insert("C");
theLinkedList.insert("D");
theLinkedList.insert("E");
theLinkedList.displayList();
System.out.println();
System.out.println(theLinkedList.search("A"));
}
}