In .NET, what does LinkedList<T> let you do through LinkedListNode<T> that List<T> cannot, and why is it rarely the faster choice?
answer
- hold the node, not the index
- AddAfter and Remove(node)
- Find still walks
- an object per item
basics
~20 sHolding a LinkedListNode<T> lets you insert beside it (AddAfter, AddBefore) or Remove it in O(1) without shifting anything. But finding a node is O(n), there is no indexer, and every item is a separate heap object.
solid answer
~40 s`LinkedList<T>` is doubly linked, and its API hands out `LinkedListNode<T>` objects from `AddLast`, `First` or `Find`. With a node in hand, `AddAfter`, `AddBefore` and `Remove(node)` are O(1), where `List<T>.Insert` and `RemoveAt` shift every later element. The catch is that the O(1) needs the node: `Find` and `Remove(T)` walk from the head, there is no indexer, and it is not an `IList<T>`. Each item is its own heap object with three references, so walking it chases pointers and adds GC work, while `List<T>` shifts one contiguous array with a fast block copy. The API also enforces ownership: a node already in a list, or one from another list, throws `InvalidOperationException`. It pays off when you keep node references, such as a dictionary of job id to node for O(1) cancellation.
code
csharp · 15 linesvar line = new LinkedList<string>();
LinkedListNode<string> flyers = line.AddLast("flyers");
line.AddLast("posters");
LinkedListNode<string> cards = line.AddLast("cards");
line.AddAfter(flyers, "rush-banner"); // O(1): we already hold the node
line.Remove(cards); // O(1): unlink by node
Console.WriteLine(string.Join(" -> ", line));
Console.WriteLine($"cards.List is null: {cards.List is null}");
var otherPrinter = new LinkedList<string>();
try { otherPrinter.AddLast(flyers); }
catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); }
otherPrinter.AddLast(cards); // a removed node may join another list
Console.WriteLine(otherPrinter.First!.Value);go deeper
Know that LinkedList<T> has no indexer and that its fast operations work on a LinkedListNode<T> you already hold.
Explain which calls are O(1) and which still walk the list, the ownership exceptions, and why List<T> usually wins on real hardware.
Justify LinkedList<T> only with a node-holding design such as id-to-node lookup, and ask for a measurement before replacing a List<T> with it.
Treat a LinkedList<T> in a hot path as a design claim that needs evidence, weighing allocation and GC cost against the shifting it avoids.
## The node is the handle `LinkedList<T>` in `System.Collections.Generic` is a **doubly linked list**: every item lives in its own `LinkedListNode<T>` object holding the value plus references to the previous node, the next node, and the list that owns it. (Internally the list is circular, with `head` pointing at the first node, but the public `Next` and `Previous` properties return `null` at the ends.) What sets it apart from `List<T>` is that the API hands you those nodes. `AddFirst`, `AddLast`, `AddBefore` and `AddAfter` return the new `LinkedListNode<T>`, and `First`, `Last` and `Find` give you existing ones. Once you hold a node you can do things a `List<T>` cannot do cheaply: - `AddAfter(node, value)` and `AddBefore(node, value)`: insert next to it in **O(1)**, with no elements shifted. - `Remove(node)`: unlink it in **O(1)**. - `node.Next`, `node.Previous`, `node.Value`: walk or edit from that point. A print shop's waiting line fits this when jobs are cancelled or reordered from the middle: keep a `Dictionary<int, LinkedListNode<PrintJob>>` from job id to node, and cancelling becomes a dictionary lookup plus `Remove(node)`, both O(1). ## What each operation costs | Operation | `LinkedList<T>` | `List<T>` | |---|---|---| | add at the end | O(1) `AddLast` | amortized O(1) `Add` | | add at the front | O(1) `AddFirst` | O(n) `Insert(0, x)` shifts everything | | insert next to a held node | O(1) `AddAfter` | O(n) `Insert(i, x)` | | remove a held node | O(1) `Remove(node)` | O(n) `RemoveAt(i)` | | remove by value | O(n) `Remove(T)` walks to find it | O(n) `Remove(T)` | | find a value | O(n) `Find`, `Contains` | O(n) `IndexOf`, `Contains` | | item at position i | no indexer | O(1) `list[i]` | The O(1) column only applies when you **already have the node**. `Remove(T value)` and `Find` start at the head and compare values with `EqualityComparer<T>.Default`, so they are linear. And `LinkedList<T>` implements `ICollection<T>` and `IReadOnlyCollection<T>` but not `IList<T>`: there is no `list[3]`. ## Ownership rules the API enforces A node belongs to at most one list, and the class checks it at run time: 1. Passing a node that is still in some list to `AddFirst`, `AddLast`, `AddBefore` or `AddAfter` as the new node throws `InvalidOperationException`: "The LinkedList node already belongs to a LinkedList." 2. Passing a node from a different list as the anchor of `AddAfter`, `AddBefore` or `Remove` throws `InvalidOperationException`: "The LinkedList node does not belong to current LinkedList." 3. After `Remove(node)`, the node's `List`, `Next` and `Previous` are cleared, so it can be added to another list. 4. `First` and `Last` return `null` on an empty list; `RemoveFirst()` and `RemoveLast()` throw `InvalidOperationException` ("The LinkedList is empty."). ## Walking and removing at the same time `foreach` over a `LinkedList<T>` uses a struct enumerator with a version check, so adding or removing during the loop makes the next step throw `InvalidOperationException` ("Collection was modified after the enumerator was instantiated."). Walking the nodes yourself avoids that, because there is no enumerator to invalidate: ```csharp for (var node = jobs.First; node != null; ) { var next = node.Next; // read before Remove clears it if (node.Value.IsCancelled) jobs.Remove(node); node = next; } ``` Capturing `next` first matters: `Remove(node)` clears the node's `Next`, so reading it afterwards would end the loop early. You can also edit an item in place through `node.Value`, with no lookup. ## Why it is rarely the faster choice The big-O table flatters `LinkedList<T>`. In practice `List<T>` usually wins, for reasons that are concrete in .NET: - **One heap object per item.** Every `LinkedListNode<T>` is a separate allocation with an object header and three references besides the value. A million items means a million objects for the garbage collector to track; a `List<T>` of a million is one array. - **Pointer chasing.** Walking the list follows references to nodes scattered across the heap, so the CPU cache helps far less than with one contiguous array. - **Shifting is a fast block copy.** `List<T>.Insert` and `RemoveAt` move the tail with one memory copy, which is quick for the sizes most code handles. - **You often do not hold the node.** If you have to `Find` it first, the O(n) walk erases the O(1) insert. So the honest guidance is: choose `LinkedList<T>` when you keep node references and perform many inserts or removals at positions you already have, such as an ordered waiting line with cancellations or a most-recently-used list paired with a dictionary. Otherwise start with `List<T>`, and measure before switching.
- How do you cancel a print job from the middle of a LinkedList<PrintJob> in O(1) when you only know its id?Keep a `Dictionary<int, LinkedListNode<PrintJob>>` alongside the list, filled from the node that `AddLast` returns. Cancelling is then a `TryGetValue`, a `Remove(node)` on the list and a `Remove(id)` on the dictionary, all O(1). Without the dictionary you would need `Find` or a walk, which is O(n).
- What happens if you pass a node from one LinkedList<T> as the anchor to another list's AddAfter?It throws `InvalidOperationException` with the message "The LinkedList node does not belong to current LinkedList." Every method that takes an anchor node checks that the node's owning list is this list, because linking around a foreign node would corrupt both lists.
- LinkedList<T> has an indexer, so list[3] is O(1).
- Remove(value) on a LinkedList<T> is O(1).
- LinkedList<T> is always faster than List<T> for inserts.
- One LinkedListNode<T> can sit in two lists at once.
- LinkedList<T>.First throws when the list is empty.