Start learning free

LESSON 65 OF 69 · PROJECTS: OBJECT-ORIENTED

Stack in C#: Build a MyStack Class with List<int>

Practice Read the full explanation

A stack is a pile where you only touch the top: the last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. Build a class MyStack that stores whole numbers in a private List<int> data = new List<int>() and offers four operations.

The methods:

  • public void Push(int value)
  • public int Pop()
  • public int Peek()
  • public int Size()

Rules:

  • push puts the value on top of the stack. It returns nothing.
  • pop removes the top value (the one pushed last) and returns it.
  • peek returns the top value but leaves it on the stack, so the size does not change.
  • size returns how many values are on the stack. A new stack has size 0, and after popping everything the size is 0 again.
  • The stack keeps working after it becomes empty: you can push again.
  • Calling pop or peek on an empty stack is not part of this exercise and the tests never do it. (In C#, indexing an empty list throws an ArgumentOutOfRangeException.)

You start with: The starter already contains the code that uses your stack (below).

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());

Expected output:

Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1

Reading the output: after pushing 10, 20 and 30 the top is 30 and the size 3. Popping gives 30, leaving size 2. Two more pops give 20 and then 10 (last in, first out), the stack is empty (size 0), and after pushing 7 the top is 7 and the size 1.


The top of the stack is the end of the list: adding and removing at the end is fast, and the last value pushed is always the last element.

List<int> has Add, an indexer (data[i]) and RemoveAt(index); the last index is data.Count - 1. Save the last value in a variable before RemoveAt, then return it.

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;
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    C# · PROJECTS: OBJECT-ORIENTED

    Stack Impl in C#, explained

    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

    1. Declare the class MyStack. The driver's new MyStack() builds an object from it.
    2. Add the private field data, a List<int> initialised to a new empty list. It is private, so outside code can only use the stack through its methods.
    3. Declare Push as a public void method taking int value.
    4. Call data.Add(value), which appends at the end.
    5. Declare Pop as a public method returning int. It must give back the top and also remove it, so its body takes three lines.
    6. Save the top in a variable named top, read with data[data.Count - 1].
    7. Remove it with data.RemoveAt(data.Count - 1). The value is already saved, so nothing is lost.
    8. Return top.
    9. Declare Peek as a public method returning int.
    10. Return the last item, data[data.Count - 1], without removing anything.
    11. Declare Size as a public method returning int.
    12. 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 Pop saves the value first. RemoveAt returns nothing (void), so the value would be lost if you removed it before reading it.
    • RemoveAt versus Remove. 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 index i, as with an array, but a list's length is Count, not Length.
    • Using List<T> needs the System.Collections.Generic namespace 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 Pop or Peek on an empty stack. If you do, the index is -1 and the list throws an ArgumentOutOfRangeException. Both methods do this in the version above, and the size stays 0.
    • Using data.Count as the index. It is one past the last element and throws. The last element is at data.Count - 1.
    • Peeking with a removal. If Peek used RemoveAt, 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 and Size() stays 1.
    • A new stack has Size() 0.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free