Wednesday 22 August 2018

C#: Stack

Stack is a collection of elements with two principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed.

How to define Stack?
Syntax
Stack stackName = new Stack();

Example
Stack tasks = new Stack();

How to add elements to Stack?
By using push method, you can add elements to stack.

Syntax
stackName.Push(object);

Example
tasks.Push(1);
tasks.push("Hello World");

How to remove elements from stack?
By using pop() method, you can remove elements from stack.pop() method remove the last element of the stack and return the removed element.

Syntax
stackName.Pop();

Example
tasks.Pop();

Program.cs
using System;
using System.Collections;

namespace collections
{
    class Program
    {

        static void Main(string[] args)
        {
            Stack tasks = new Stack();

            tasks.Push("task1");
            tasks.Push("task2");
            tasks.Push("task3");
            tasks.Push("task4");

            Console.WriteLine("Number Of Elements in Stack are {0}", tasks.Count);
            Console.WriteLine("Last Element of the Stack {0}", tasks.Pop());
            Console.WriteLine("Last Element of the Stack {0}", tasks.Pop());
            Console.WriteLine("Last Element of the Stack {0}", tasks.Pop());
            Console.WriteLine("Last Element of the Stack {0}", tasks.Pop());
            Console.WriteLine("Number Of Elements in Stack are {0}", tasks.Count);

        }
    }
}

Output
Number Of Elements in Stack are 4
Last Element of the Stack task4
Last Element of the Stack task3
Last Element of the Stack task2
Last Element of the Stack task1
Number Of Elements in Stack are 0

Following table summarizes important properties and methods of Stack class.

Property
Description
Count
Gets the number of elements contained in the Stack.

Following table summarizes all the methods in Stack collection.
                
Method
Description
Clear()
Removes all objects from the Stack.
Clone()
Creates a shallow copy of the Stack.
Contains(Object)
Return true, if the element exists in stack, else false.
Peek()
Returns the object at the top of the Stack without removing it.
Pop()

Removes and returns the object at the top of the Stack.
Push(Object)
Inserts an object at the top of the Stack.
ToArray()
Copies the Stack to a new array.

If you want to know complete properties and methods details of Stack class, please go through following link.


Previous                                                 Next                                                 Home

No comments:

Post a Comment