Linked List Deletion
Typer | Posted on | |
public class LinkedListDeletion {
// Static nested class for node
public static class IntNode {
int data;
IntNode link;
public IntNode(int data, IntNode link) {
this.data = data;
this.link = link;
}
}
// Print the list
public static void printList(IntNode head) {
if (head == null) {
System.out.println("null");
return;
}
IntNode current = head;
while (current != null) {
System.out.print(current.data + " → ");
current = current.link;
}
System.out.println("null");
}
// Delete node by value
public static IntNode deleteByValue(IntNode head, int target) {
if (head == null) {
return null;
}
if (head.data == target) {
return head.link;
}
IntNode current = head;
while (current.link != null && current.link.data != target) {
current = current.link;
}
if (current.link != null) {
current.link = current.link.link;
}
return head;
}
// Create 10 → 15 → 7
public static IntNode buildInitialList() {
return new IntNode(10, new IntNode(15, new IntNode(7, null)));
}
public static void main(String[] args) {
// Delete head
System.out.println("Delete head node (10):");
IntNode list1 = buildInitialList();
System.out.print("Before: ");
printList(list1);
list1 = deleteByValue(list1, 10);
System.out.print("After: ");
printList(list1);
// Delete middle
System.out.println("\nDelete middle node (15):");
IntNode list2 = buildInitialList();
System.out.print("Before: ");
printList(list2);
list2 = deleteByValue(list2, 15);
System.out.print("After: ");
printList(list2);
// Delete tail
System.out.println("\nDelete tail node (7):");
IntNode list3 = buildInitialList();
System.out.print("Before: ");
printList(list3);
list3 = deleteByValue(list3, 7);
System.out.print("After: ");
printList(list3);
}
}