Shining Star Services LLC
C# Custom LinkedList PrintLifo method and C# Operators - Learning C# - Part 4
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 this article, we define our PrintLifo method to print nodes from the top of the stack. We will also 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.


   public void PrintLifo()
   {
   LinkedList node = Head;
   for (int i = size; i > 0 && node != null; i--)
   {
   Console.WriteLine("Category: {0} Item: {1}",
   node.Category(), node.Item());
   node = node.Next;
   }
   }


In our above PrintLife() method, we create a new node, and assign it to our existing Head node. We will use a for statement to loop through our nodes, finding the previous node by using the "node.Next" value.

   for (int i = size; i > 0 && node != null; i--)


In our "for" loop, we define a new integer value "i" and set it to the size of our linked list. We then loop as long as "i" is greater than 0 and the node is not null or empty. On each loop we decrement our counter with "i--." In this one statement we are making use of assignment operators: i = size and i--. We are also using the relational operator ">" to see if "i" is greater than 0. And we are using the equality operator "!=" to see if the node is null or not.

C# uses several such operators. Think of the word: CREAM.
Conditional Operators &&, ||
Relational Operators  <, >, <=, >=
Equality Operators ==, !=
Assignment Operators =, +=, -=, *=, /=
Mathematical Operators +, -, *, /

In our next article we will print our linked list in first in first out order and create a helper method GetNode() which allows us to retrieve a specific node by position.

Nannette

© Copyright 1997-2017 Shining Star Services LLC, Nannette Thacker. All Rights Reserved.