Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Doubly Linked List Implementation in Swift

11 min readbeginner
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Doubly Linked List runs in O(1) insert time and O(n) space, in Swift as in every other language.
  • ✓Nothing. The standard library has no linked list of any kind, and Array is a contiguous copy-on-write buffer.
  • ✓Mark the node class final, which lets the compiler use static dispatch instead of going through the class vtable on every property access.
  • ✓The Swift trap: Automatic Reference Counting is reference counting with no cycle collector at all, so a node holding a strong prev and a strong next keeps its neighbours alive and the entire list leaks, permanently and silently.
  • ✓Every node is a heap-allocated class instance with a 16-byte header and an atomic reference count, and the counts are updated on every assignment, which on a multi-threaded traversal means real contention.

What Doubly Linked List actually is

A doubly linked list stores each element in its own node carrying a value plus a pointer to the previous node and a pointer to the next one. That second pointer is the whole story: it buys O(1) deletion when you already hold the node, which is the only reason to choose this structure over an array, and it costs you the property that every node is referenced exactly once. Languages split sharply along that second line. The ones that free memory by counting references cannot free a doubly linked list at all without help, because two nodes pointing at each other keep each other alive forever. The ones with a tracing collector do not care. And the ones that ship a node handle in their standard library are the only ones where the O(1) deletion is actually reachable from application code, because a list that hides its nodes forces you back to an O(n) search to find the thing you wanted to delete.

Doubly Linked List in Swift: what you actually reach for

Nothing. The standard library has no linked list of any kind, and Array is a contiguous copy-on-write buffer. Apple ships a Deque in the separate swift-collections package, which covers the double-ended case without nodes.

Swift implementation

Mark the node class final, which lets the compiler use static dispatch instead of going through the class vtable on every property access. Declare prev as unowned when the list owns the node and the node cannot outlive the list, and as weak only when it genuinely can become nil.
swift
final class DllNode<T> {
    var value: T
    // next is strong: the list owns the chain going forward.
    var next: DllNode<T>?
    // prev MUST NOT be strong. Two strong links in opposite directions
    // form an ARC cycle, and ARC has no cycle collector: the list would
    // leak in full, forever.
    unowned(unsafe) var prev: DllNode<T>?

    init(_ value: T) { self.value = value }
}

final class DoublyLinkedList<T> {
    private(set) var head: DllNode<T>?
    private(set) var tail: DllNode<T>?
    private(set) var count = 0

    @discardableResult
    func append(_ value: T) -> DllNode<T> {
        let node = DllNode(value)
        node.prev = tail
        tail?.next = node
        tail = node
        if head == nil { head = node }
        count += 1
        return node
    }

    func remove(_ node: DllNode<T>) {
        let prev = node.prev
        let next = node.next
        if let prev { prev.next = next } else { head = next }
        if let next { next.prev = prev } else { tail = prev }
        node.next = nil
        count -= 1
    }
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Swift-specific trap

Automatic Reference Counting is reference counting with no cycle collector at all, so a node holding a strong prev and a strong next keeps its neighbours alive and the entire list leaks, permanently and silently. Nothing in the compiler warns about it, and the only way to see it is the Leaks instrument. Making prev weak fixes the cycle but adds a side-table indirection on every read; unowned is cheaper because it stores no side-table entry, at the cost of a hard trap if the referent is already gone.

Performance in Swift, beyond the O(1) insert

Every node is a heap-allocated class instance with a 16-byte header and an atomic reference count, and the counts are updated on every assignment, which on a multi-threaded traversal means real contention. Reading a weak reference is measurably more expensive than reading an unowned one because it must consult the side table to decide whether the object is still alive. The asymptotic cost is the same in every language, O(1) insert time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Doubly Linked List between languages.

Real-World Applications

Doubly Linked List applies wherever its problem shape appears in your own code. In Swift, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Doubly Linked List helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Doubly Linked List appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Doubly Linked List over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Doubly Linked List to build pattern recognition. In Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

Frequently Asked Questions

Which Swift type or library should I use for Doubly Linked List?

Nothing. The standard library has no linked list of any kind, and Array is a contiguous copy-on-write buffer. Apple ships a Deque in the separate swift-collections package, which covers the double-ended case without nodes.

What is the most common Swift mistake when implementing Doubly Linked List?

Automatic Reference Counting is reference counting with no cycle collector at all, so a node holding a strong prev and a strong next keeps its neighbours alive and the entire list leaks, permanently and silently. Nothing in the compiler warns about it, and the only way to see it is the Leaks instrument. Making prev weak fixes the cycle but adds a side-table indirection on every read; unowned is cheaper because it stores no side-table entry, at the cost of a hard trap if the referent is already gone.

How does Doubly Linked List actually perform in Swift?

Every node is a heap-allocated class instance with a 16-byte header and an atomic reference count, and the counts are updated on every assignment, which on a multi-threaded traversal means real contention. Reading a weak reference is measurably more expensive than reading an unowned one because it must consult the side table to decide whether the object is still alive. Time complexity is O(1) insert and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

If you are a student, see what GitHub Copilot offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.