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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.