Curriculum
In C#, a Stack is a collection that represents a last-in, first-out (LIFO) stack of objects. Elements can be pushed onto the top of the stack and popped off the top of the stack. Here’s an example of using a Stack to store and manipulate a collection of strings:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// Create a stack of strings
Stack<string> names = new Stack<string>();
// Push some names onto the stack
names.Push("Alice");
names.Push("Bob");
names.Push("Charlie");
// Display the top name on the stack
Console.WriteLine("Top name on the stack: {0}", names.Peek());
// Pop a name off the stack and display it
string poppedName = names.Pop();
Console.WriteLine("Popped name: {0}", poppedName);
// Display the remaining names on the stack
Console.WriteLine("Remaining names on the stack:");
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
In this example, we first create an empty Stack<string> object called names. We then use the Push method to add some names to the stack. We use the Peek method to display the top name on the stack without removing it. We use the Pop method to remove and return the top name on the stack, which we store in the poppedName variable. Finally, we use a foreach loop to display the remaining names on the stack.
Here are some other useful methods provided by the Stack class:
Count: Returns the number of elements in the stack.Contains: Determines whether an element is in the stack.Clear: Removes all elements from the stack.ToArray: Copies the elements of the stack to a new array.Here’s an example that demonstrates some of these methods:
// Create a stack of integers
Stack<int> numbers = new Stack<int>();
// Push some numbers onto the stack
numbers.Push(1);
numbers.Push(2);
numbers.Push(3);
// Check if the stack contains a certain number
if (numbers.Contains(2))
{
Console.WriteLine("Stack contains the number 2");
}
// Create an array from the stack and display it
int[] numberArray = numbers.ToArray();
Console.WriteLine("Array from stack: [{0}]", string.Join(", ", numberArray));
// Clear the stack
numbers.Clear();
// Display the number of elements in the stack (which should be 0)
Console.WriteLine("Number of elements in stack: {0}", numbers.Count);
It’s important to note that Stack provides many other useful properties and methods for working with stacks, such as TrimExcess to optimize the internal array to the actual number of elements, GetEnumerator to get an enumerator that iterates through the stack, and CopyTo to copy the elements of the stack to an existing array.