Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 20 Linked Lists Richard Gesick.

Similar presentations


Presentation on theme: "Lecture 20 Linked Lists Richard Gesick."— Presentation transcript:

1 Lecture 20 Linked Lists Richard Gesick

2 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.

3 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 ; }

4 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

5 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.

6 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");

7 doubly linked lists data data data data data head tail

8 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.

9 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();

10 Traversing with a foreach loop
public static void PrintList1(LinkedList<string> L) { foreach (string s in L) Console.Write(s + " "); Console.WriteLine(); }


Download ppt "Lecture 20 Linked Lists Richard Gesick."

Similar presentations


Ads by Google