May 12, 2025
Node Class:
int data and Node next.data and sets next to null.LinkedList Class:
Node head to represent the start of the list.class LinkedList {
Node head;
static class Node {
int data;
Node next;
Node(int d) { data = d; }
}
static LinkedList insert(LinkedList list, int data) {
Node new_node = new Node(data);
if (list.head == null) {
list.head = new_node;
} else {
Node last = list.head;
while (last.next != null) {
last = last.next;
}
last.next = new_node;
}
return list;
}
}
static void printList(LinkedList list) {
Node currNode = list.head;
System.out.print("LinkedList: ");
while (currNode != null) {
System.out.print(currNode.data + " ");
currNode = currNode.next;
}
System.out.println();
}
Key at Head:
head.next and free memory of the old head.Key in Middle/End:
prev.next.Key Not Found: No deletion performed.
static LinkedList deleteByKey(LinkedList list, int key) {
Node currNode = list.head, prev = null;
if (currNode != null && currNode.data == key) {
list.head = currNode.next;
return list;
}
while (currNode != null && currNode.data != key) {
prev = currNode;
currNode = currNode.next;
}
if (currNode != null) {
prev.next = currNode.next;
}
return list;
}
Index 0:
head.next and free memory of the old head.Index within Bounds:
Index Out of Bounds: No deletion performed.
static LinkedList deleteAtPosition(LinkedList list, int index) {
Node currNode = list.head, prev = null;
if (index == 0 && currNode != null) {
list.head = currNode.next;
return list;
}
int counter = 0;
while (currNode != null) {
if (counter == index) {
prev.next = currNode.next;
break;
} else {
prev = currNode;
currNode = currNode.next;
counter++;
}
}
return list;
}
The implementation of a linked list in Java involves creating a Node class for individual elements and a LinkedList class to manage the nodes. Key operations include insertion, traversal, and deletion by key or position, each requiring careful manipulation of pointers to ensure the integrity of the list.