Shining Star Services LLC
C# Custom LinkedList Push and Pop Methods - Learning C# - Part 3
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 this article, we define our Push and Pop methods. Our Push method allows us to add an Inventory item to our list on the top of the stack. We define PopLifo and PopFifo (last in first out and first in first out) methods.


   public int Push(string invCategory, string invItem)
   {
   // add the Inventory to the list
   LinkedList node = new LinkedList();
   node.inventoryCategory = invCategory;
   node.inventoryItem = invItem;
   node.Next = Head;  // set the Next pointer to the 
   // last item previously added
   Head = node;   // set the Head as the item just now added
   return size++;  // increment the size of the list
   }


We create our Push method as public, and it returns the size of our list as an integer. We pass two parameters to our method: the category and item.

In our first statement, we create a new "node." Since we are making it a LinkedList type, that means it consists of its own category, item, and Next value. In our next statement, as we type the word "node." intellisense provides the different properties defined in the LinkedList, thus allowing us to easily populate these items. We set our node.inventoryCategory value, etc.

Our node.Next is assigned to our previously added node as stored in "Head." And our Head node is reassigned with the values we just entered.

We increment our size counter and return the value.

In our Pop methods, we aren't actually "deleting" anything. Let's take a look:


   public void PopLifo()   // LIFO
   {
   if (size > 0)
   {
   LinkedList node = Head;
   Head = node.Next;   // assign pointer to the head to the previous second node
   size--;   // decrement the counter
   }
   }

In our PopLifo method, we remove the last node added to the list. To do so, we first want to see if our size is greater than zero, using the ">" relational operator. If so, we create a new node and assign it to our "Head." We then reassign our Head, or top of the list, to point to the node that Head was pointing to, our "node.Next." Then we decrement our size of our list.

   public void PopFifo()
   {
   if (size > 0)   // don't allow to keep decrementing counter if list is empty
   size--;   // decrement the counter to remove it from displaying in the list (won't traverse to this node)
   }

Removing our node from the "first in" node on the list is much simpler. We simply decrement our size by one so that when we traverse through the nodes we never hit it.

In Part 4 of our series we will Print our list to the screen.

Nannette


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