Data Structures and Database Applications Linked Lists
LinkedList System.Collections.Generic.LinkedList Automatic resizing and homogeneous list Represents a doubly linked list of nodes
Object References Recall that an object reference is a variable that stores the address of an object A reference also can be called a pointer References often are depicted graphically: student John Smith 40725 3.58
References as Links Object references can be used to create links between objects Suppose a class contains a reference to another object of the same class: class Node { Object info; Node next; }
References as Links References can be used to create a variety of linked structures, such as a linked list:
Using Intermediate Nodes The objects being stored should not be concerned with the details of the data structure in which they may be stored For example, a list of students created with a Student class should not have to store a link to the next Student object in the previous Student object Instead, a separate node class is used in the LinkedList class which serves two functions: It has a reference to the data object (e.g the Student object) It has a link to the next (and possibly previous) nodes in the list The internal representation becomes a linked list of nodes
Inserting a Node Internally, a node is inserted into a linked list with a few reference changes:
Deleting a Node Likewise, a node is removed from a linked list by changing the next pointer of the preceding node:
Other Dynamic Representations When a linked list structure has both next and previous references, it is a doubly linked list: class Node { Object info; Node next; Node prev; }
LinkedList Example: LinkedList<string> sentence = new LinkedList<string>(); // instantiates ls object sentence.AddFirst("fox"); // add "fox" as first item sentence.AddLast("jumped"); // add “jumped" as last item sentence.AddLast("dog"); // add “dog" as new last item sentence.AddBefore(sentence.Last, "the"); // add “the” before “dog” LinkedListNode<string> current = sentence.First; while (current.Next != null) // loop through all values { Console.Write(current.Value + " "); current = current.Next; } // prints: fox jumped the dog Console.WriteLine();
LinkedList Example (continued): sentence.AddAfter(sentence.First.Next, "over"); // add "over" after "jumped" sentence.AddFirst("the"); // add "the" as first word LinkedListNode<string> current = sentence.First; while (current.Next != null) { Console.Write(current.Value + " "); current = current.Next; } // now prints: the fox jumped over the dog Console.WriteLine(); Console.ReadLine();
Other Dynamic Representations Internally, a linked list can also use a separate header node, which can store the amount of nodes (count) and references to both the front and rear of the list:
Common LinkedList Methods AddAfter() AddBefore() AddFirst() AddLast() Remove() RemoveFirst() RemoveLast() Clear() Contains() Find() FindLast()