Example – reversing words

For the first example, let's try to reverse a word using a stack. You can do this by iterating through characters that form a string, adding each at the top of the stack, and then removing all elements from the stack. At the end, you receive the reversed word, as shown in the following diagram, which presents the process of reversing the MARCIN word:

The implementation code, which should be added to the Main method within the Program class, is shown in the following code snippet:

Stack<char> chars = new Stack<char>(); foreach (char c in "LET'S REVERSE!") { chars.Push(c); } while (chars.Count > 0) { Console.Write(chars.Pop()); ...

Get C# Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.