Write a program to reverse a word using stack
For example
Input:
We United
Output:
eW detinU
Solution
using System;
using System.Collections.Generic;
namespace StackOperation
{
class Program
{
public static void Main()
{
Console.WriteLine("Enter a string");
var str = Console.ReadLine();
Console.WriteLine("Reverse of given string");
ReverseWords(str);
Console.ReadLine();
}
public static void ReverseWords(string str)
{
var st = new Stack<char>();
foreach (var t in str)
{
if (t != ' ')
{
st.Push(t);
}
else
{
while (st.Count > 0)
{
Console.Write(st.Pop());
}
Console.Write(" ");
}
}
while (st.Count > 0)
{
Console.Write(st.Pop());
}
}
}
}