Junior — Middle
Can you explain what a singly linked list is and how it works?
sobes.tech AI
Answer from AI
A singly linked list is a data structure consisting of nodes, where each node contains data and a reference to the next node in the list. Unlike an array, elements are not stored in contiguous memory cells but are linked through pointers.
It works as follows: you have the first node (the head of the list), which has a reference to the next node, and so on, until the last node points to null, indicating the end of the list.
Example in Dart (Flutter):
class Node<T> {
T data;
Node<T>? next;
Node(this.data);
}
void main() {
var first = Node<int>(1);
var second = Node<int>(2);
var third = Node<int>(3);
first.next = second;
second.next = third;
// Traversing the list
var current = first;
while (current != null) {
print(current.data);
current = current.next!;
}
}
This list is convenient for dynamic addition and removal of elements, but accessing elements by index requires sequential traversal.