LinkedList<T>
Learn doubly linked lists with LinkedList<T>.
Doubly LinkedList<T>
A LinkedList<T> is a doubly linked list; each node points to both its predecessor and successor. AddFirst adds at the head, AddLast at the tail. RemoveFirst and RemoveLast trim the ends.
Adding at either end is O(1); inserting in the middle requires a node reference. There is no indexed access; reaching an item means walking from the head. It suits queue and stack needs well.
Adding nodes and iterating
AddFirst("cherry") creates a new node and places it at the head; the old head becomes the second node. A foreach walks the list from head to tail; each step yields node.Value.
To insert in the middle, AddAfter and AddBefore take a LinkedListNode<T> reference. First and Last return the end nodes; they return null when the list is empty.
Exercise Add a node and iterate a LinkedList
Two items were added to list below with AddLast. Use AddFirst to insert "cherry", then print each value with foreach and Console.WriteLine.
Show example solution
Add cherry at the head with AddFirst, then iterate the list and print each item.
Example solution:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = new LinkedList<string>();
list.AddLast("apple");
list.AddLast("pear");
list.AddFirst("cherry");
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}
Test yourself
-
Match the method to its direction
- AddFirst
- Add to head
- AddLast
- Add to tail
- RemoveFirst
- Remove head
- RemoveLast
- Remove tail
-
What is the advantage of LinkedList<T>?
- Fast add at head/tail
- Fast indexed access
- Less memory
- Automatic sorting
Show answer
Fast add at head/tail — Correct. LinkedList adds at head or tail in O(1).
-
Complete the AddFirst call
list.Add____("cherry");Show answer
list.AddFirst("cherry");