C# Custom LinkedList PrintFifo method and GetNode by Position - Learning C# - Part 5

In Part 1 of this series, we created a console application and an abstract class. In Part 2 we setup our LinkedList derived class and defined our properties and setup our constructor. In Part 3, we defined our Push and Pop methods. We implemented both a PopLifo and PopFifo method. In part 4 we defined our PrintLifo method to print nodes from the top of the stack. We also discussed C# Operators.

In this article we will define a PrintFifo() method, which will use a GetNode() helper method to find specific nodes, allowing us to print nodes from the bottom of the stack.

To print our list in "first in first out" order, since our linked list contains pointers to the previously added node on the list, we have no direct means to access the first node on the list, so we will create a "GetNode()" method to find a specific node by position.

   private LinkedList GetNode(int position)
   // traverse thru list until reach the node at the position passed in
   // loop until reach the position just before the position desired, 
   // and return the .Next node, which is the position desired
   LinkedList node = Head;  // start with the last item added
   for (int i = 1; i < position && node != null; i++)
   node = node.Next;
   return node;

Our GetNode method will return a LinkedList at the position passed in as a parameter. We create a new node, which we assign to the Head node. Then we loop, beginning at 1, until 1 is greater than the position passed in or our node is not null, and we increment our counter as we loop through nodes. With each loop, we reassign our node to the node stored in the node.Next. Once we hit the node just prior to the position desired, we assign our node to the node.Next value -- which is the desired node -- and we return our node.

   public void PrintFifo()
   for (int i = size; i > 0; i--)
   LinkedList node = this.GetNode(i);
   Console.WriteLine("Category: {0} Item: {1}",
   node.Category(), node.Item());

Now we are ready to use the GetNode() method in our PrintFifo() method to print our list in "first in first out" order. Again, we use a "for" loop to loop through the nodes beginning with the node at the bottom of the stack -- the one in our linked list "size." We create a new node and assign it to the value returned from GetNode(i).

We then utilize the Console.WriteLine() method to print our values to the screen. Utilizing {0} {1} etc. allows us to leave a placeholder for the values following the string you want printed. In our example, the category name retrieved from the node.Category() method will print in the {0} position and the value retrieved from the node.Item() method wil print in the {1} position.

In our next article, we will create a FindItems() method which will print a listing to the screen of all items based on the category or item name.


No Comments