
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
236
|
Chapter 4: Generics
4.6 Implementing a Linked List
Problem
You need a linked data structure that allows you to easily add and remove elements.
Solution
Use the generic LinkedList<T> class. The following method creates a LinkedList<T>
class, adds nodes to this linked list object, and then uses several methods to obtain
information from nodes within the linked list:
public static void UseLinkedList( )
{
// Create a new LinkedList object.
LinkedList<TodoItem> todoList = new LinkedList<TodoItem>( );
// Create TodoItem objects to add to the linked list.
TodoItem i1 = new TodoItem("paint door", "Should be done third");
TodoItem i2 = new TodoItem("buy door", "Should be done first");
TodoItem i3 = new TodoItem("assemble door", "Should be done second");
TodoItem i4 = new TodoItem("hang door", "Should be done last");
// Add the items.
todoList.AddFirst(i1);
todoList.AddFirst(i2);
todoList.AddBefore(todoList.Find(i1), i3);
todoList.AddAfter(todoList.Find(i1), i4);
// Display all items.
foreach (TodoItem tdi in todoList)
{
Console.WriteLine(tdi.Name + " : " + tdi.Comment);
}
// Display information from the second node in the linked list.
Console.WriteLine("todoList.First.Next.Value.Name == " +
todoList.First.Next.Value.Name);
// Display information from the next to last node in the linked ...