Problem overview
A stack is a pile where you only touch the top. The last value you put in is the first one you take out: last in, first out. You build a class MyStack for int values with four methods:
Push(int value)puts a value on top and returns nothing.Pop()removes the top value and returns it.Peek()returns the top value and leaves it in place.Size()returns how many values the stack holds.
In the driver, the values 10, 20 and 30 go in. Peek() shows 30 and Size() is 3. Three pops give 30, then 20, then 10, and the size is 0. After pushing 7, the top is 7 and the size is 1.
Approach: the end of a list is the top
The stack keeps its values in a private List<int> data. A List<T> grows when you add to it, which an array can't do. Adding and removing at the end of a list is cheap, so the end of data is the top of the stack. The value pushed last is then always the last element, which is exactly the one Pop and Peek must return.
The last index is data.Count - 1: with three values it is 2. Count is a property, so it has no parentheses, unlike the Size() method you write yourself.
Step by step
- Declare the class
MyStack. The driver'snew MyStack()builds an object from it. - Add the private field
data, aList<int>initialised to a new empty list. It is private, so outside code can only use the stack through its methods. - Declare
Pushas a publicvoidmethod takingint value. - Call
data.Add(value), which appends at the end. - Declare
Popas a public method returningint. It must give back the top and also remove it, so its body takes three lines. - Save the top in a variable named
top, read withdata[data.Count - 1]. - Remove it with
data.RemoveAt(data.Count - 1). The value is already saved, so nothing is lost. - Return
top. - Declare
Peekas a public method returningint. - Return the last item,
data[data.Count - 1], without removing anything. - Declare
Sizeas a public method returningint. - Return
data.Count. One list item is one stack value.
Watching the list
This is the content of data after each operation in the driver, with the top at the right end:
Push 10 [10]
Push 20 [10, 20]
Push 30 [10, 20, 30]
Pop [10, 20]
Pop [10]
Pop []
Push 7 [7]
Each push appends and each pop removes the last element, so the values leave in the reverse of the order they arrived.
The solution in C#
class MyStack {
private List<int> data = new List<int>();
public void Push(int value) {
data.Add(value);
}
public int Pop() {
int top = data[data.Count - 1];
data.RemoveAt(data.Count - 1);
return top;
}
public int Peek() {
return data[data.Count - 1];
}
public int Size() {
return data.Count;
}
}
class Solution {
public void MainFunction() {
MyStack s = new MyStack();
s.Push(10);
s.Push(20);
s.Push(30);
Console.WriteLine("Top: " + s.Peek());
Console.WriteLine("Size: " + s.Size());
Console.WriteLine("Pop: " + s.Pop());
Console.WriteLine("Size: " + s.Size());
Console.WriteLine("Pop: " + s.Pop());
Console.WriteLine("Pop: " + s.Pop());
Console.WriteLine("Empty size: " + s.Size());
s.Push(7);
Console.WriteLine("Top: " + s.Peek());
Console.WriteLine("Size: " + s.Size());
}
}
The program prints:
Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1
C# details
- Why
Popsaves the value first.RemoveAtreturns nothing (void), so the value would be lost if you removed it before reading it. RemoveAtversusRemove.RemoveAt(index)removes by position.Remove(value)removes the first element equal to a value, which is a different job and would pick the wrong item when values repeat.- The list indexer.
data[i]reads the element at indexi, as with an array, but a list's length isCount, notLength. - Using
List<T>needs theSystem.Collections.Genericnamespace in a standalone file. The lesson's editor already has it available.
Complexity
Every method takes O(1) time on average. Add at the end is amortised constant: the list sometimes reallocates, but rarely enough to average out. Reading by index, RemoveAt on the last index and Count all take constant time, because no other element has to move. Removing from the front instead would shift every remaining element, which is O(n). The stack uses O(n) space for n values.
Why not use the list directly?
A caller holding a List<int> could insert in the middle or remove from the front, and then the structure would no longer behave like a stack. Because data is private, the only operations available are the four methods, and each one touches the top. That restriction is what makes it a stack.
Edge cases and common mistakes
- Empty stack. The tests never call
PoporPeekon an empty stack. If you do, the index is -1 and the list throws anArgumentOutOfRangeException. Both methods do this in the version above, and the size stays 0. - Using
data.Countas the index. It is one past the last element and throws. The last element is atdata.Count - 1. - Peeking with a removal. If
PeekusedRemoveAt, the size would change after every look. - Reading the front.
data[0]is the oldest value, which would make this a queue, not a stack. - Reuse after empty. Nothing special is needed: after the stack empties,
Push(7)works and the top is 7 with size 1.
Testing
- Push 1, 2, 3 and pop three times to get 3, 2, 1: reverse order.
- Push 5, then call
Peek()twice: both give 5 andSize()stays 1. - A new stack has
Size()0.
