Thursday, April 18, 2024 00:54

Table of contents >> Data Structures > Stack

Stack

Stack is a linear data structure in which there are 3 operations defined: adding an element at the top of the stack (push), removing an element from the top of the stack (pop) and inspect the element from the top without removing it (peek). All these operations are very fast – it takes a constant time to execute them. The stack does not support the operations search and
access through index. The stack is a data structure which has a LIFO behavior (last in, first out). It is used when we have to model such a behavior – for example, if we have to keep the path to the current position in a recursive search. Use a stack when you have to implement the behavior “last in, first out” (LIFO).

Like an List, a stack has an add and get method, with a slight difference in behavior.

To add to a stack data structure, you need to use the Push() call, which is the Add() equivalent of an List. Retrieving a value is slightly different. The stack has a Pop() call, which returns and removes the last object added. If you want to check the top value in a Stack, use the Peek() call.

There are two formats to define a Stack in C#:

The difference between them is that the simple Stack structure will work with Objects, while the Stack<T> one will accept only a specified type.

Here is the C# code to add and traverse through a Stack data structure:

If you run the above C# code, you see that the list is returned in the order: “three”, “two”, “one”.

These are the main methods of a Stack:

Push() – Usually the first action you need to do on Stack is Push elements into it. The word Push is a computer science term that means “add to the top.”

Pop(), Peek() – Here we Pop and Peek. When you call Pop(), the elements from the top of the Stack is returned, and the element is removed from the collection.

Clear() – is a parameterless method. It erases the Stack’s contents.

Contains() – We search the Stack with the Contains() method. The Contains method on Stack returns true if the element is found.

The most important property of a Stack is:

Count – gives the number of elements in a Stack.

The value null is allowed in Stacks with reference types such as string. You can also assign your Stack to null instead of calling Clear(). When assigning to null, the contents are not changed. Instead the reference is unrooted in the garbage collector. When you call Pop() or Peek() on your Stack, the runtime will throw an exception if the Stack has zero elements. To work around this problem, you must check the Count property. Here we catch the exception raised by this situation (we haven’t learn about exceptions yet, but just consider them a special kind of errors):

Tags: ,

Leave a Reply



Follow the white rabbit