Junior — Middle
How to determine before the last element in a singly linked list?
sobes.tech AI
Answer from AI
In a singly linked list, to find the element before the last, you need to traverse the list and stop at the node whose next node is the last one (i.e., the next node's Next field is null).
Example in C#:
class Node {
public int Value;
public Node Next;
}
Node FindPenultimate(Node head) {
if (head == null || head.Next == null) return null; // no penultimate
Node current = head;
while (current.Next.Next != null) {
current = current.Next;
}
return current;
}
Here, the loop continues as long as the next node has a next, i.e., until we reach the penultimate element.