Implementing a Custom Linked List Class from Scratch in Java
In this article, we will seen
How to create Node Class
Create Insert method and Add data in Custom Linked list Class
Print All elements of Linked list
Linked list is linear data structure, means it stores values in linear manner but like Arrays it does not store elements at contiguous location.
Linked list class represent as node and node contains value and reference of next and previous node.
You can learn about Linked list class in details :
List interface and Linked list class
Lets start with creating singly custom linked list class.
Step 1 : Create Node class
class Node {
//Data in the current node
int value;
//Reference for the next node
Node next;
Node(int value) {
this.value = value;
}
}
Step 2 : Create Custom Linked list class, Add insert() and printList() methods
class CustomLinkedList {
Node head;
public void insert(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
} else {
Node node = head;
while(node.next != null) {
node = node.next;
}
node.next = newNode;
}
}
public static void printList(CustomLinkedList list) {
Node currNode = list.head;
// Traverse through the LinkedList
while (currNode != null) {
// Print the data at current node
System.out.print(currNode.value + " ");
// Go to next node
currNode = currNode.next;
}
}
}
Step 3 : Create Main class and Call CustomeLinkedList class insert() and printList() method
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Size of LinkedList");
int size = sc.nextInt();
System.out.println("Enter Data in LinkedList");
// Creating CustomLinkedList object and storing Node
CustomLinkedList obj = new CustomLinkedList();
for (int i = 0; i < size; i++) {
obj.insert(sc.nextInt());
}
// Print Linked list elements
obj.printList(list);
}
}
Output :
Enter Size of LinkedList
6
Enter Data in LinkedList
1 2 3 6 5 4
1 2 3 6 5 4
________________________
Enter Size of LinkedList
10
Enter Data in LinkedList
10 2 30 60 8 55 9 66 94 25
10 2 30 60 8 55 9 66 94 25
RECOMMENDED ARTICLES :
- Guide to Collection framework in Java with Examples
- Reverse Linked List (LL) using Iterative (While loop) and Recursive approach in Java
- Merging two sorted Linked List using Recursion approach with Stack trace
Comments
Post a Comment