Linked Lists Slides
Linked Lists Slides
Linked Lists Slides
Robert Horvick
SOFTWARE ENGINEER
@bubbafat www.roberthorvick.com
What are linked lists?
Overview - Nodes
- Node chains
1
null
Node head = new Node(1);
1 2
next null
Node head = new Node(1);
1 2 3
next next null
Singly Linked List
A linked list that provides forward iteration from the
start to the end of the list.
class LinkedListNode<TNode> {
node2.Previous = node1;
node3.Previous = node2;
ints.AddHead(i);
ints.AddHead(i);
ints.AddHead(i);
ints.AddHead(i);
ints.AddHead(i);
public void AddHead(T value) Adding a value to the head (start) of the list
{
Allocate the new node
DoublyLinkedListNode<T> adding = new DoublyLinkedListNode
<T>(value, null, head);
ints.AddTail(i);
ints.AddTail(i);
ints.AddTail(i);
ints.AddTail(i);
ints.AddTail(i);
public void AddTail(T value) Adding a value to the tail (end) of the list
{
if (tail == null) If the list is empty defer to AddHead
{
AddHead(value);
}
else
{
DoublyLinkedListNode<T> adding = new Allocate the node being added
DoublyLinkedListNode<T>(value, tail);
tail.Next = adding; Point the current tail’s next to the new node
Count++;
Increment the Count value (items in the list)
}
}
Finding Items
Finding Items
while(current != null) {
if(current.Value.Equals(value))
return current;
current = current.Next;
}
return null;
}
1 2 3
1 3
? null
null ?
Removing a Node
1 3
next null
null prev
Remove algorithm
Demo - Find the node to delete
- Remove the found node
Three Cases
- Empty list
- Single node
- Multiple nodes
Enumeration
Enumeration
GetEnumerator()
1 2 3 4 5
1 2 3 4 5
GetReverseEnumerator()
LinkedList<int> ints = LinkedList<int>(); Create a list of integers
ints.AddTail(3);
}
LinkedList<int> ints = LinkedList<int>(); Create a list of integers
ints.AddTail(3);
ints.GetReverseEnumerator())
}
Sorted List
A doubly linked list where the values are inserted and
stored in sort-order.
Adding Sorted Items
sorted.Add(3);
sorted.Add(2);
sorted.Add(5);
sorted.Add(4);
sorted.Add(1);
sorted.Add(3);
sorted.Add(2);
sorted.Add(5);
sorted.Add(4);
sorted.Add(1);
sorted.Add(3);
sorted.Add(2);
sorted.Add(5);
sorted.Add(4);
sorted.Add(1);
sorted.Add(3);
sorted.Add(2);
sorted.Add(5);
sorted.Add(4);
sorted.Add(1);
sorted.Add(3);
sorted.Add(2);
sorted.Add(5);
sorted.Add(4);
sorted.Add(1);
No
No
No
Find Insert
Insert
Point
Demo Replace the Contact Manager storage
array with a sorted list
- Removes size limit
- Contacts are implicitly sorted
- Code is simplified by not managing
the array storage
Lists are nodes chains together
Operations
- Adding and removing
- Enumeration
- Searching