Write a program to Sort 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 = Sort(st);
Console.WriteLine("Sort Stack");
foreach (var i in st)
Console.WriteLine(i);
Console.ReadLine();
}
public static Stack<T> Sort<T>(Stack<T> input) where T : IComparable<T>
{
var tmpStack = new Stack<T>();
while (input.Any())
{
var tmp = input.Pop();
while (tmpStack.Any() && GreaterThen(tmpStack.Peek(), tmp))
{
input.Push(tmpStack.Pop());
}
tmpStack.Push(tmp);
}
return tmpStack;
}
static bool GreaterThen<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) < 0;
}
}
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();
}
}
}