August 16, 2022 Custom LinkedList Implementation in Java What is Linked List ? A linked list is a linear data structure containing interconnected nodes through pointers. Since there is no concept of pointers in Java, each node holds the reference of another node, but the last element of the linked list refers to NULL, meaning the end of the list. A linked list can grow and shrink in size dynamically without wasting any memory. Hence, we prefer a linked list for quick insertion and deletion, unlike an Array List. A linked list is memory efficient, but takes some extra memory for pointers that points to the next node. Linked List Node Implementation public class Node { private int data; private Node nextNode; public Node(int data){ this.data = data; } public int getData() { return data; } public void setData(int data) { this.data = data; } public Node getNextNode() { return nextNode; } public void setNextNode(Node nextNode) { this.nextNode = nextNode; } } public class CustomLinkedList { Node head; class Node{ int data; Node next; public Node(int data){ this.data = data; } } public void insert(int data){ Node newNode = new Node(data); if(this.head == null){ head = newNode; }else { Node currentNode = head; while(currentNode.getNextNode() != null){ currentNode = currentNode.getNextNode(); } currentNode.setNextNode(newNode); } } public void insertHead(int data){ Node newNode = new Node(data); newNode.setNextNode(head); head = newNode; } public void insertAt(int index, int data){ Node nodeToBeInserted = new Node(data); Node node = head; for(int i = 0; i< index -1; i++){ node = node.getNextNode(); } nodeToBeInserted.setNextNode(node.getNextNode()); node.setNextNode(nodeToBeInserted); } public void display(){ if(head != null){ Node currentNode = head; while(currentNode.getNextNode() != null){ System.out.println(currentNode.getData()); currentNode = currentNode.getNextNode(); } System.out.println(currentNode.getData()); } } public void deleteNodeAt(int index){ Node node = head; for(int i = 0; i< index -1; i++){ node = node.getNextNode(); } node.setNextNode(node.getNextNode().getNextNode()); } public Node reverse(){ Node previous = null; Node current = head; Node next; while (current != null){ next = current.getNextNode(); current.setNextNode(previous); previous = current; current = next; } return previous; } } public class LinkedListRunner { public static void main(String [] args){ CustomLinkedList customLinkedList = new CustomLinkedList(); customLinkedList.insert(5); customLinkedList.insert(10); customLinkedList.insert(15); customLinkedList.insert(20); customLinkedList.display(); customLinkedList.insertAt(2, 100); System.out.println("********"); customLinkedList.display(); System.out.println("********"); customLinkedList.deleteNodeAt(2); customLinkedList.display(); System.out.println("********"); customLinkedList.insertHead(50); customLinkedList.display(); } } Algorithm Java Algorithmcustom linkedlistdata structuredatastructurelinkedlist