- Linked List is made of combination of Node
- The smallest unit of linked list is Node
- Node contains two things the content of the node And reference to next node
- If a linked list has only one element then it would have only one node
Node.java
class Node{
String content;
Node next;
public Node(String content){
this.content = content;
}
}
- To traverse linked list we should always start at the head
- After printing the content we should move to next node as mentioned in next variable in current node
Traversing a LL
LL node next always points to reference of next node if any or else would be null if only one element is present. While Traversing we always start with head position
public class Main{
public static void main(String args[]){
Node node1 = new Node("Anbu");
Node node2 = new Node("Arul");
node1.next = node2;
Node node3 = new Node("Arasu");
node2.next = node3;
printLinkedList(node1);
}
public static void printLinkedList(Node startingNode){
while(startingNode.next !=null){
System.out.println(startingNode.content);
startingNode = startingNode.next;
}
if(startingNode.next == null){
System.out.println(startingNode.content);
}
}
}
The above code can be refactored as below using recursion calling same function again and again
public class Main{
public static void main(String args[]){
Node node1 = new Node("Anbu");
Node node2 = new Node("Arul");
node1.next = node2;
Node node3 = new Node("Arasu");
node2.next = node3;
printLinkedList(node1.head);
}
public static void printLinkedList(Node startingNode){
//Note: We are traversing to next null node before exit without this last element wont be printed
if(startingNode == null){
return;
}
System.out.println(startingNode.content);
printLinkedList(startingNode.next);
}
}
Output
Anbu Arul Arasu
Now let’s move the linked list methods to a separate class called SimpleLinkedList.java
SimpleLinkedList.java
public class SimpleLinkedList {
Node head;
public static void traverseLinkedList(Node startingNode){
//Note: We are traversing to next null node before exit without this last element wont be printed
if(startingNode == null){
return;
}
System.out.println(startingNode.content);
printLinkedList(startingNode.next);
}
}