Stack Implementation using Linked List

Write a program to demonstrate stack Implementation using Linked List.

Solution:

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

namespace StackOperation
{
    public class Program
    {
        public static void Main()
        {
            var st = new Stack<int>();
            st.Push(1);
            st.Push(2);
            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>
    {
        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 void Clear()
        {
            _list.Clear();
        }

        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 *