Sobes.tech
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 elements (nodes), each of which contains data and a reference (pointer) to the next element in the list. Unlike arrays, the elements of a linked list are not necessarily stored in contiguous memory.

Example of a singly linked list in Swift:

class Node {
    var value: Int
    var next: Node?

    init(value: Int) {
        self.value = value
    }
}

// Creating a list: 1 -> 2 -> 3
let first = Node(value: 1)
let second = Node(value: 2)
let third = Node(value: 3)
first.next = second
second.next = third

This list allows efficient insertion and deletion of elements without shifting the others, but access to elements by index requires sequential traversal.