class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } class LinkedList { Node head; void append(int data) { if (head == null) { head = new Node(data); return; } Node current = head; while (current.next != null) { current = current.next; } current.next = new Node(data); } void deleteByValue(int value) { if (head == null) return; if (head.data == value) { head = head.next; return; } Node current = head; while (current.next != null && current.next.data != value) { current = current.next; } if (current.next != null) { current.next = current.next.next; } } void printList() { Node current = head; while (current != null) { System.out.print(current.data + " -> "); current = current.next; } System.out.println("null"); } } public class Main { public static void main(String[] args) { LinkedList list = new LinkedList(); list.append(1); list.append(2); list.append(3); list.append(4); list.deleteByValue(3); list.printList(); } }
The method deleteByValue searches for the node with the value 3 and removes it by linking the previous node directly to the next node. So the list after deletion is 1 -> 2 -> 4 -> null.
LinkedList list = new LinkedList(); list.append(1); list.append(2); list.append(3); list.deleteByValue(1); list.printList();
Since the head node has the value 1, deleting it moves the head pointer to the next node, which has value 2. So the list becomes 2 -> 3 -> null.
void deleteByValue(int value) { if (head == null) return; if (head.data == value) { head = head.next; return; } Node current = head; while (current.next != null && current.next.data != value) { current = current.next; } if (current.next != null) { current.next = current.next.next; } }
The loop stops when current.next is null or current.next.data matches the value. If the last node's value matches, current.next is not null, so it deletes correctly. But if the loop condition was wrong, it might skip checking the last node. Here, the code is correct, so the question is to confirm understanding that the loop condition allows deletion of the last node.
LinkedList list = new LinkedList(); list.append(1); list.append(2); list.append(3); list.deleteByValue(5); list.printList();
Since 5 is not in the list, the deleteByValue method does nothing and the list remains unchanged: 1 -> 2 -> 3 -> null.
In the worst case, the node to delete is at the end or not present, so we traverse all n nodes, making the time complexity O(n).
