Stacks C# Help

A stack is another container that is very similar to the queue. You just use different methods to access the stack. The item that is added last to the stack is read first. The stack is a last in,first out (LIFO) container.

It shows the representation of a stack where the Push () method adds an item to the stack, and the Pop () m:!hod gets the item that was added last.

Capture

Similar to the queue classes, the non-generic Stack class implements the interfaces ICollection, . IEnurnerable, and ICloneablei the generic Stack<T> class implements the interfaces
IEnurnerable<T>, ICollection, and IEnurnerable. Members of the Stack and Stack<T> class are listed in the following table.

Capture

In this example, three items are added to the stack with the Push ( )\method. With the foreach method, all items are iterated using the IEnumerable interface. The enumerator of the stack does not remove the items; it just returns item by item.

Stack<char> alphabet = new Stack<char>();
alphabet. Push ( ,A ‘ ) ;
alphabet.Push(‘B’);
~phabet.Push(‘C’) ;
foreach (char item in alphabet)
( –
.Console.Write(item) ;
}
Console.WriteLine();

Because the items are read in the order from the last added to the first, the following result is produced:

CBA

Reading the items with the enumerator does not change the state of the items. With the Pop () method.” every item that is read is also removed from the stack. This way you can iterate the collection using a while loop and verify the Count property if items are still existing:

Stack<char> alphabet = new Stack<char>();
alphabet.Push(‘A’);
alphabet.Push(‘B’);
alphabet. Push ( ‘C ‘ ) ;
Console.Write(OFirst iteration: 0);
foreach (char item.in alphabet)
(
Console.Write(item);

}

Console.WriteLine();
Console.Write(·Second iteration: .);
while (alphabet.Count > 0)
(
Console.Write(alphabet.Pop());
}
Console.WriteLine();

The result gives CBA twice, once for each iteration. After the second iteration, the stack is empty because the second iteration used the Pop () method:

First iteration: CBA
Second iteration: CBA

Posted on October 29, 2015 in Collections

Share the Story

Back to Top