Junior — Middle
How can you extract the last node from a linked list?
sobes.tech AI
Answer from AI
To extract the last node from a linked list in Java, you need to traverse the list from the head to the node where the next field is null. This node will be the last.
Example method for a singly linked list:
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public Node getLastNode(Node head) {
if (head == null) return null;
Node current = head;
while (current.next != null) {
current = current.next;
}
return current;
}
This method returns the last node or null if the list is empty.