Delete element from stack

Write a program to delete an element from a stack.

Solution

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

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);

            st.Remove(5);

            Console.WriteLine("After Deletion element from Stack");
            foreach (var i in st)
                Console.WriteLine(i);

            Console.ReadLine();
        }

    }




    public class Stack<T> : IEnumerable<T>
    {
        readonly LinkedList<T> _list = new LinkedList<T>();

        public void Push(T value)
        {
            _list.AddFirst(value);
        }
        public T Pop()
        {
            if (_list.Count == 0)
            {
                throw new InvalidOperationException("The Stack is empty");
            }
            var value = _list.First.Value;
            _list.RemoveFirst();
            return value;
        }

        public T Peek()
        {
            if (_list.Count == 0)
            {
                throw new InvalidOperationException("The Stack is empty");
            }
            return _list.First.Value;
        }

        public int Count()
        {
            return _list.Count;
        }


        public void Remove(T i)
        {
            _list.Remove(i);
        }

        public IEnumerator<T> GetEnumerator()
        {
            return _list.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _list.GetEnumerator();
        }
    }
}

Leave a Reply

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