I am new to data structures. While learning it, I am at a point where I am not able to understand the difference between these two implementations of linked lists.
Wherever I have seen mostly, everyone is using the first implementation of linked list which is mentioned below.
By two classes:
class Node{
int data;
int value;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
Node(int data, Node next){
this.next = next;
this.data = data;
}
}
class LinkedList{
Node head;
LinkedList(Node head){
this.head = head;
}
LinkedList(){
this.head = null;
}
void insert(int data){
//it will insert at the end
//logic
}
//Other methods.
}
But here is my question, why do we need two classes to implement it. Let's say if I use below implementation:
class Node{
int data;
int value;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
Node(int data, Node next){
this.next = next;
this.data = data;
}
void appendToTail(int d){
Node node = new Node(4);
Node traversal = this;
while(traversal.next!=null){
traversal = traversal.next;
}
traversal.next = n;
}
}
Now I can do all the things with it in single class isn't it? Please tell me what's the problem with this approach because its making very confused.
The one-class method looks rather limiting, does it not? The benefits of using a Linked List is for an easy way to access the head and tail of it. Having a Linked List improves runtime significantly, rather than going through each Node to find the tail. When it comes to deletion, which is definitely a crucial topic in a data structures course, the two-class method is much much more practical than the one-class method. In the two-class method, you can iterate through and reassign heads or tails as you please. In the one-class method, whichever node you create first means everything, and because you can't have a defined head or tail, keeping track of all the Nodes after deletions occur becomes significantly challenging. TLDR: two-class method allows for much easier access and in turn, faster runtimes.