Iterate over a stack in C#
This post will discuss how to iterate over a stack in C#.
1. Using while loop
A simple solution is to remove and process the stack’s items using the standard pop function, one at a time, until the stack gets empty. The problem with this solution is that it pops items from the stack container and then prints them, resulting in the stack becoming empty at the end. This can be avoided by creating a copy of the stack object and processing the copy. This way the original stack remains untouched, but its copy becomes empty.
|
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 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Stack<int> stack = new Stack<int>(); stack.Push(1); stack.Push(2); stack.Push(3); stack.Push(4); stack.Push(5); // create a copy of the stack Stack<int> stk_cpy = new Stack<int>(stack.ToArray()); // print stack while (stk_cpy.Count > 0) { int top = stk_cpy.Pop(); Console.WriteLine(top); } } } |
Output:
5
4
3
2
1
2. Using foreach loop
A better solution is to iterate over the stack using a foreach loop. The foreach statement provides a simple, clean way to iterate through the elements of a container. The following example shows its usage by enumerating over the stack in LIFO order without disturbing its contents.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Stack<int> stack = new Stack<int>(); stack.Push(1); stack.Push(2); stack.Push(3); stack.Push(4); stack.Push(5); // print stack foreach (int i in stack) { Console.WriteLine(i); } } } |
Output:
5
4
3
2
1
That’s all about iterating over a stack in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)