Implement Stack using an Array

Write a program to demonstrate stack Implementation using an Array.

Solution:

using System;
using System.Collections;
using System.Collections.Generic;

namespace StackOperation
{
    class Program
    {
        public static void Main()
        {
            var st = new Stack<int>();
            st.Push(1);
            st.Push(2);
            st.Push(5);
            st.Push(3);
            st.Push(4);

            Console.WriteLine("Stack:");
            foreach (var i in st)
                Console.WriteLine(i);

            Console.ReadLine();
        }

    }

    public class Stack<T> : IEnumerable<T>
    {
        private T[] _items = new T[0];
        private int _size;

        public void Push(T value)
        {
            if (_size == _items.Length)
            {
                var length = _size == 0 ? 4 : _size * 2;
                var array = new T[length];   
                _items.CopyTo(array, 0);
                _items = array;
            }
            _items[_size] = value;
            _size++;
        }
        public T Pop()
        {
            if (_size == 0)
            {
                throw new InvalidOperationException("Empty");
            }
            _size--;
            return _items[_size];
        }

        public T Peek()
        {
            if (_size == 0)
            {
                throw new InvalidOperationException("Empty");
            }
            return _items[_size - 1];
        }

        public void Clear()
        {
            _size = 0;
        }

        public IEnumerator<T> GetEnumerator()
        {
            for (var i = _size - 1; i >= 0; i--)
            {
                yield return _items[i];
            }
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *