Complete the code to create a linked list node with a value.
class Node { int value; Node next; Node(int val) { this.value = [1]; this.next = null; } }
The constructor assigns the passed value val to the node's value field.
Complete the code to add a new node at the end of the linked list.
void append(int newValue) {
Node newNode = new Node(newValue);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.[1] != null) {
current = current.next;
}
current.next = newNode;
}We traverse the list by moving through the next pointers until we find the last node.
Fix the error in the code to correctly insert a node at the beginning of the linked list.
void insertAtBeginning(int newValue) {
Node newNode = new Node(newValue);
newNode.next = [1];
head = newNode;
}The new node's next should point to the current head before updating head to the new node.
Fill both blanks to complete the method that counts the number of nodes in the linked list.
int countNodes() {
int count = 0;
Node current = head;
while (current [1] null) {
count[2];
current = current.next;
}
return count;
}The loop runs while current is not null, and count is incremented each time.
Fill all three blanks to complete the method that searches for a value in the linked list and returns true if found.
boolean contains(int target) {
Node current = head;
while (current != null) {
if (current.[1] == [2]) {
return [3];
}
current = current.next;
}
return false;
}We check if the current node's value equals the target and return true if found.
