Lecture 20 Linked Lists Richard Gesick
Linked Lists Dynamic data structures can grow and shrink at execution time. A linked list is a linear collection (i.e., a sequence) of nodes, connected by reference links (“chained together”). It can be singly or doubly linked A linked list is appropriate when the number of data elements is unpredictable. Linked lists become full only when the system has insufficient memory.
Nodes A self-referential class contains a member that refers to an object of the same class type. In the class declaration Next references an object of type Node, an object of the same type being declared. Next is referred to as a link. class Node { public string data; public Node next ; }
Common tasks include: Inserting to the front Inserting to the end Inserting in between the front/end Deleting Searching Sorting Each of these tasks takes different amounts of time depending upon how the linked list is implemented
A Singly Linked List A backslash indicates a null link. Not setting the link in the last node of a list to null is a logic error.
C# doubly linked list The linked list class in C# is a generic and doubly linked which means that we have direct access to the front and the end of the linked list. LinkedList<string> LL1 = new LinkedList<string>(); LL1.AddFirst("a"); LL1.AddLast("c");
doubly linked lists data data data data data head tail
Nodes The nodes of the linked list are called LinkedListNodes and are also generic. LinkedListNode<string> myNode = LL1.First; First and Last are properties of the LinkedList class that allow direct access to the first and last nodes respectively.
Traversing by Node using Iteration public static void PrintList (LinkedList<string> L) { LinkedListNode<string> myNode = L.First; while (myNode != null) { Console.Write(myNode.Value + " "); myNode = myNode.Next; } Console.WriteLine();
Traversing with a foreach loop public static void PrintList1(LinkedList<string> L) { foreach (string s in L) Console.Write(s + " "); Console.WriteLine(); }