Complete the code to delete the first node of a singly linked list.
public void deleteAtBeginning() {
if (head == null) {
return;
}
head = [1];
}To delete the first node, we move the head pointer to the next node.
Complete the code to print the linked list after deleting the first node.
public void printList() {
Node current = head;
while (current != [1]) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}The loop should continue until current is null, which means end of list.
Fix the error in the deleteAtBeginning method to avoid NullPointerException.
public void deleteAtBeginning() {
if (head == null) {
return;
}
Node temp = head;
head = head.next;
[1] = null;
}Setting the old head to null helps garbage collection and avoids dangling references.
Fill both blanks to complete the method that deletes the first node and returns its data.
public int deleteAtBeginning() {
if (head == null) {
return -1;
}
int data = head.data;
Node temp = head;
head = [1];
[2] = null;
return data;
}Move head to next node, then set old head (temp) to null to delete it.
Fill all three blanks to implement a safe delete at beginning that handles empty list and returns deleted node data.
public Integer deleteAtBeginning() {
if (head == [1]) {
return [2];
}
int deletedData = head.data;
Node oldHead = head;
head = [3];
oldHead = null;
return deletedData;
}Check if head is null (empty list), return -1. Otherwise, move head to next node and delete old head.
