O'Reilly logo

C# Data Structures and Algorithms by Marcin Jamro

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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()); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required