+ 1

Generics > Generic Classes: Section III

class Stack<T> { int index = 0; T[] innerArray = new T[100]; public void Push(T item) { innerArray[index++] = item; } public void T Pop() { return innerArray[--index]; } public T Get(int k) { return innerArray[k]; } } Stack<int> intStack = new Stack<int>(); intStack.Push(3); intStack.Push(6); intStack.Push(7); Console.WriteLine(intStack.Get(1)); //Outputs 6 So, basically every time you "Push()" the code adds to a position/index to the array (or list)? So, if I push two (2) more items into the list, and then want to retrieve that item, "Console.WriteLine(intStack.Get(4))" would work? As you start counting on zero (0). What does the Pop() do? How would you remove an item or overwrite it?

3rd Mar 2017, 4:06 AM
William Draper
William Draper - avatar
1 Odpowiedź
+ 1
The implementation of Pop as shown here simply returns the item on top of the stack and decrements the index. A traditional stack would also remove the value from the stack, but this code doesn't do that. Since this is a generic though, how you destroy those values depends on the type. Integers would be set to 0 for example, but for strings you would set them to null. However, as your implementation stands, you CAN Push new values to overwrite the old ones (and then Pop() again to decrement the index). It's cumbersome to do this of course though and not very efficient. Take a look at the following code. As you can see, even though 6 was popped off the stack, I can still access it with the Get method. That's because your method Pop does not destroy the value it returns. And, you can't really do so with an integer stack anyway. You can only reset them to 0. A string stack, on the other hand, can have its values destroyed by null. using System; namespace SoloLearn { class Stack<T> { int index = 0; T[] innerArray = new T[100]; public void Push(T item) { innerArray[index++] = item; } public T Pop() { return innerArray[--index]; } public T Get(int k) { return innerArray[k]; } } class Program { static void Main() { Stack<int> intStack = new Stack<int>(); intStack.Push(3); intStack.Push(6); intStack.Push(7); Console.WriteLine(intStack.Pop()); // Outputs 7 Console.WriteLine(intStack.Pop()); // Outputs 6 Console.WriteLine(intStack.Get(1)); // Outputs 6 } } }
7th Mar 2017, 1:41 PM
Anthony Vanover
Anthony Vanover - avatar