Bird
Raised Fist0
DSA C#programming

Peek Top Element of Stack in DSA C#

Choose your learning style10 modes available
Mental Model
A stack is like a pile of plates where you only see and use the top plate. Peeking means looking at the top plate without removing it.
Analogy: Imagine a stack of books on a table. You can only see the top book and peek means to look at the title of the top book without taking it off.
Top -> [ 5 ] -> [ 3 ] -> [ 7 ] -> null
          ↑
        peek here
Dry Run Walkthrough
Input: stack: push 5, push 3, push 7; peek top element
Goal: To see the top element of the stack without removing it
Step 1: push 5 onto empty stack
Top -> [ 5 ] -> null
Why: We start with one element on the stack
Step 2: push 3 onto stack
Top -> [ 3 ] -> [ 5 ] -> null
Why: New element goes on top, previous top moves down
Step 3: push 7 onto stack
Top -> [ 7 ] -> [ 3 ] -> [ 5 ] -> null
Why: New element is now the top of the stack
Step 4: peek top element
Top -> [ 7 ] -> [ 3 ] -> [ 5 ] -> null
Why: Peeking shows the top without changing the stack
Result:
Top -> [ 7 ] -> [ 3 ] -> [ 5 ] -> null
Peeked element: 7
Annotated Code
DSA C#
using System;

public class StackNode
{
    public int Data;
    public StackNode Next;

    public StackNode(int data)
    {
        Data = data;
        Next = null;
    }
}

public class Stack
{
    private StackNode top;

    public Stack()
    {
        top = null;
    }

    public void Push(int data)
    {
        StackNode newNode = new StackNode(data);
        newNode.Next = top; // new node points to current top
        top = newNode; // top moves to new node
    }

    public int Peek()
    {
        if (top == null)
            throw new InvalidOperationException("Stack is empty");
        return top.Data; // return data at top without removing
    }

    public override string ToString()
    {
        StackNode current = top;
        string result = "Top -> ";
        while (current != null)
        {
            result += "[ " + current.Data + " ] -> ";
            current = current.Next; // move to next node
        }
        result += "null";
        return result;
    }
}

public class Program
{
    public static void Main()
    {
        Stack stack = new Stack();
        stack.Push(5);
        stack.Push(3);
        stack.Push(7);
        Console.WriteLine(stack.ToString());
        int topElement = stack.Peek();
        Console.WriteLine("Peeked element: " + topElement);
    }
}
newNode.Next = top; // new node points to current top
link new node to current top to keep stack order
top = newNode; // top moves to new node
update top pointer to new node for push
if (top == null) throw new InvalidOperationException("Stack is empty");
check empty stack before peek to avoid error
return top.Data; // return data at top without removing
peek returns top element without changing stack
current = current.Next; // move to next node
traverse stack nodes to build string representation
OutputSuccess
Top -> [ 7 ] -> [ 3 ] -> [ 5 ] -> null Peeked element: 7
Complexity Analysis
Time: O(1) because peek only reads the top element without traversal
Space: O(n) because stack stores n elements in linked nodes
vs Alternative: Compared to popping, peek does not remove elements so it is faster and safer when only viewing is needed
Edge Cases
empty stack
throws InvalidOperationException to signal no elements to peek
DSA C#
if (top == null)
    throw new InvalidOperationException("Stack is empty");
When to Use This Pattern
When you need to see the last added item without removing it, use the peek operation on a stack to get it instantly.
Common Mistakes
Mistake: Trying to peek from an empty stack without checking causes runtime error.
Fix: Always check if the stack is empty before peeking and handle the empty case properly.
Summary
Peek returns the top element of the stack without removing it.
Use peek when you want to see the last added item but keep it in the stack.
The key insight is that peek reads the top pointer's data without changing the stack structure.

Practice

(1/5)
1. What does the Peek() method do in a stack?
easy
A. Returns the top element without removing it
B. Removes and returns the top element
C. Adds a new element to the top
D. Checks if the stack is empty

Solution

  1. Step 1: Understand the Peek method purpose

    The Peek method is designed to look at the top element of the stack without changing the stack itself.
  2. Step 2: Differentiate from Pop method

    Unlike Pop, Peek does not remove the element; it only returns it.
  3. Final Answer:

    Returns the top element without removing it -> Option A
  4. Quick Check:

    Peek() returns top element without removal [OK]
Hint: Peek shows top without removing it [OK]
Common Mistakes:
  • Confusing Peek with Pop
  • Thinking Peek adds elements
  • Assuming Peek empties the stack
2. Which of the following is the correct syntax to peek the top element of a stack named myStack in C#?
easy
A. var top = myStack.Pop();
B. var top = myStack.Top();
C. var top = myStack.Peek();
D. var top = myStack.GetTop();

Solution

  1. Step 1: Recall Stack method names in C#

    The Stack class in C# uses Peek() to look at the top element without removing it.
  2. Step 2: Verify method correctness

    Top(), GetTop() are not valid Stack methods; Pop() removes the element.
  3. Final Answer:

    var top = myStack.Peek(); -> Option C
  4. Quick Check:

    Peek() is correct syntax for top element [OK]
Hint: Use Peek() method to get top element [OK]
Common Mistakes:
  • Using Pop() instead of Peek()
  • Using non-existent methods like Top()
  • Missing parentheses after Peek
3. What will be the output of the following C# code?
Stack<int> numbers = new Stack<int>();
numbers.Push(10);
numbers.Push(20);
numbers.Push(30);
Console.WriteLine(numbers.Peek());
Console.WriteLine(numbers.Count);
medium
A. 10 3
B. 30 3
C. 20 2
D. 30 2

Solution

  1. Step 1: Trace the Push operations

    Elements pushed in order: 10, then 20, then 30. Stack top is 30.
  2. Step 2: Evaluate Peek and Count

    Peek returns top element 30 without removing it. Count remains 3 as no Pop occurred.
  3. Final Answer:

    30 3 -> Option B
  4. Quick Check:

    Peek = 30, Count = 3 [OK]
Hint: Peek shows last pushed; Count unchanged by Peek [OK]
Common Mistakes:
  • Assuming Peek removes element
  • Confusing Count after Peek
  • Mixing order of pushed elements
4. Identify the error in this code snippet that tries to peek the top element of a stack:
Stack<string> stack = new Stack<string>();
string top = stack.Peek;
Console.WriteLine(top);
medium
A. Peek removes the element, so top is null
B. Stack is not initialized properly
C. Console.WriteLine cannot print stack elements
D. Peek is used without parentheses, causing a syntax error

Solution

  1. Step 1: Check method call syntax

    Peek is a method and must be called with parentheses: Peek()
  2. Step 2: Identify error type

    Using Peek without parentheses causes a compile-time syntax error.
  3. Final Answer:

    Peek is used without parentheses, causing a syntax error -> Option D
  4. Quick Check:

    Method calls need () [OK]
Hint: Always use parentheses when calling methods [OK]
Common Mistakes:
  • Forgetting parentheses on Peek
  • Assuming Peek removes element
  • Thinking Console.WriteLine can't print strings
5. Given a stack Stack<char> letters with elements 'a', 'b', 'c' pushed in that order, write the output after this code:
char top1 = letters.Peek();
letters.Pop();
char top2 = letters.Peek();
Console.WriteLine(top1);
Console.WriteLine(top2);
Console.WriteLine(letters.Count);
hard
A. c b 2
B. a b 3
C. c c 3
D. b a 1

Solution

  1. Step 1: Trace initial stack and first Peek

    Stack after pushes: bottom 'a', then 'b', top 'c'. Peek() returns 'c' as top1.
  2. Step 2: Pop removes top element 'c'

    After Pop(), top 'c' is removed. Stack top is now 'b'.
  3. Step 3: Second Peek returns 'b' as top2

    Peek() now returns 'b'. Count is 2 because one element was removed.
  4. Final Answer:

    c b 2 -> Option A
  5. Quick Check:

    Peek then Pop then Peek updates top correctly [OK]
Hint: Peek shows current top; Pop removes it; next Peek shows new top [OK]
Common Mistakes:
  • Assuming Peek removes element
  • Confusing order of elements after Pop
  • Miscounting stack size after Pop
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard