Reverse Stack Implementation

Write a program to reverse stack.

For example

Input:
 1  2  3  4 

 Output:
 4  3  2  1

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

            Reverse(st);

            Console.WriteLine("Reversed Stack");
            foreach (var i in st)
            {
                Console.WriteLine(i);
            }

            Console.ReadLine();
        }

        static void Reverse<T>(Stack<T> st)
        {
            if (st.Any())
            {
                T x = st.Peek();
                st.Pop();
                Reverse(st);


                InsertAtEnd(st, x);
            }
        }

        static void InsertAtEnd<T>(Stack<T> st, T x)
        {

            if (!st.Any())
                st.Push(x);
            else
            {
                var a = st.Peek();
                st.Pop();
                InsertAtEnd(st, x);
                st.Push(a);
            }
        }
    }

    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 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 *