Friday, May 17, 2019

C# : Data structure : Stack


Stack Implementation in C#

public class Stack
    {
        readonly int  _capacity;
        int top;
        int[] _stack ;
        public int Top
        {
            get { return top; }
        }
        public Stack()
        {
            _capacity = 1000;
            top = -1;
        }
        public Stack( int capacity)
        {
            _capacity = capacity;
            _stack = new int[_capacity];
            top = -1;
        }
        public void Push(int item)
        {
            if (top < _capacity - 1)
            {
                _stack[top + 1] = item;
                top++;
            }
            else
            {
                Console.WriteLine("Stack is full");
            }
        }
        public int Pop()
        {
            int itemToReturn=-1;
            if (top == -1)
            {
                Console.WriteLine("Stack empty!!");
             
            }
            else
            {
                 itemToReturn= _stack[top];
                top--;
             
            }
            return itemToReturn;
        }
        public int Peek()
        {
            if (top != -1)
            {
                return _stack[top];
            }
            else
            {
                Console.Write("Stack is empty!!!");
                return -1;

            }

         

        }

No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...