In this post, we will learn how to reverse string using a stack.
This is an important interview question.
Let’s have a look at the implementation in C#.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
class Program { public static String Reverse(String str) { char[] charArr = str.ToCharArray(); int size = charArr.Length; Stack stack = new Stack(size); int i; for (i = 0; i < size; ++i) { stack.Push(charArr[i]); } for (i = 0; i < size; ++i) { charArr[i] = (char)stack.Pop(); } return String.Join("",charArr); } public static void Main() { string str = "Hello, World!!!"; Console.WriteLine(str); str = Reverse(str); Console.WriteLine(str); Console.ReadLine(); } } |
Output:
Output:
1 2 3 4 |
Hello, World!!! !!!dlroW ,olleH |