Junior — Middle
Can you explain what a linked list is and how it is structured?
sobes.tech AI
Answer from AI
A 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 arrays, linked lists do not require a contiguous block of memory and allow efficient insertion and deletion of elements.
Main types of linked lists:
- Singly linked list: each node contains a reference only to the next node.
- Doubly linked list: each node contains references to both the next and previous nodes.
Example of a singly linked list in JavaScript (Node.js):
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
add(value) {
const newNode = new Node(value);
if (!this.head) {
this.head = newNode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
}
}
Linked lists are useful when dynamic resizing of the structure and frequent insertions/deletions are required.