Loading...

Stacks Collection in Data Structures Using Built-in Functions of C#


Stacks in Data Structures:


Stack is a collection same as list but it is a LIFO (Last In First Out) Collection. It means the element that is entered in a stack at last will the come out at first position. In more easy words whenever we push (insert) an element in the stack will Pop (remove) first whenever we want to delete and element of the stack. It will work like this because Push will insert elements is top of a stack and after new element is inserted the top element will go down and new element takes the top place and Pop deletes the element at the top of the stack which is the newest one.

Basic Stack Operations:

  • New()      : Creates a new Stack.
  • Push()      : Inserts Object or element in the top of the stack.
  • Pop()        : Deletes Object or element from the top of the stack.
  • Peek()      : Returns the Object or element in the top of the                            Stack but does not delete it from the Stack.
  • Size()        : Returns the number of Object or element in the                          Stack i.e. Size of the Stack
  • IsEmpty() : It is a Boolean Function, It Indicates that the Stack is empty or not.

Code of Stack Collection in C#:

class Code
    {
        Stack<int> numbers = new Stack<int>(); // initialization, int is the data type and numbers is the name of stack
        public void working()
        {
            numbers.Push(100); //100 will be entered in the top of stack
            Console.WriteLine("100 is pushed");
            display();

            numbers.Push(200); // 200 wiil bw entere and now 200 is on top
            Console.WriteLine("200 is pushed");
            display();

            numbers.Push(300); // now 300 is on top of the stack
            Console.WriteLine("300 is pushed");
            display();

            numbers.Pop(); // top (Last inserted) value 300 will be deleted and 200 will become the last(top) value
            Console.WriteLine("300 is poped");
            display();

            numbers.Pop(); // 200 will be deleted and 100 will become the top value
            Console.WriteLine("200 is poped");
            display();
        }
        public void display()
        {
            Console.WriteLine("Stack : ");
            foreach (int a in numbers) // displaying all stack members using foreach loop
            {
                Console.WriteLine(a);
            }
            Console.WriteLine();
        }
    }
class Program
        {
            static void Main(string[] args)
            {
                Code c = new Code();
                c.working();

            }
        }

Output:




Hit Like Button if you understood, It helps a lot to keep us Motivated.

0 comments:

Post a Comment

Google+

 
TOP