Junior — Middle
Can you explain what a linked list is and its main features?
sobes.tech AI
Answer from AI
A linked list is a data structure consisting of nodes, where each node contains data and a reference (or references) to the next (and/or previous) node. Main features:
- Dynamic memory allocation: the size of the list can change during runtime.
- Elements are not stored in contiguous memory cells but are linked through pointers.
- Fast addition and removal of elements in the middle of the list without shifting other elements.
- No direct access by index; to get an element, you need to traverse from the beginning through links.
Example of a singly linked list in C#:
class Node {
public int Data;
public Node Next;
public Node(int data) {
Data = data;
Next = null;
}
}
class LinkedList {
public Node Head;
public void Add(int data) {
Node newNode = new Node(data);
if (Head == null) {
Head = newNode;
} else {
Node current = Head;
while (current.Next != null) {
current = current.Next;
}
current.Next = newNode;
}
}
}