C# Custom LinkedList PrintLifo method and C# Operators - Learning C# - Part 4
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.
- Download Source Code on CodePlex: CSLinkedList.zip
- C# Custom LinkedList Console Application and Abstract Base Class and Method - Learning C# - Part 1
- C# Custom LinkedList Derived Classes, Constructor Initializations - Learning C# - Part 2
- C# Custom LinkedList Push and Pop Methods - Learning C# - Part 3
- C# Custom LinkedList PrintLifo method and C# Operators - Learning C# - Part 4
- C# Custom LinkedList PrintFifo method and GetNode by Position - Learning C# - Part 5
- C# Custom LinkedList FindItems() method - Learning C# - Part 6
- C# Custom LinkedList Main() method - Learning C# - Part 7
[CSLINKEDLIST]