Bird
Raised Fist0
DSA Cprogramming

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 and touch the top book. Peeking is just looking at the title of the top book without taking it off.
Top -> [ 3 ] -> [ 2 ] -> [ 1 ] -> null
          ↑
        (top)
Dry Run Walkthrough
Input: stack: push 1, push 2, push 3; peek top element
Goal: To see the top element of the stack without removing it
Step 1: push 1 onto empty stack
Top -> [ 1 ] -> null
          ↑
Why: We start by adding the first element, which becomes the top
Step 2: push 2 onto stack
Top -> [ 2 ] -> [ 1 ] -> null
          ↑
Why: New element goes on top, pushing previous top down
Step 3: push 3 onto stack
Top -> [ 3 ] -> [ 2 ] -> [ 1 ] -> null
          ↑
Why: Again, new element becomes the top
Step 4: peek top element
Top -> [ 3 ] -> [ 2 ] -> [ 1 ] -> null
          ↑
Why: Peeking shows the top element without changing the stack
Result:
Top -> [ 3 ] -> [ 2 ] -> [ 1 ] -> null
Top element is 3
Annotated Code
DSA C
#include <stdio.h>
#include <stdlib.h>

// Node structure for stack
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// Push element onto stack
void push(Node** top_ref, int data) {
    Node* new_node = (Node*)malloc(sizeof(Node));
    new_node->data = data;
    new_node->next = *top_ref;
    *top_ref = new_node;
}

// Peek top element without removing
int peek(Node* top) {
    if (top == NULL) {
        printf("Stack is empty\n");
        return -1; // Indicate empty stack
    }
    return top->data;
}

// Print stack elements
void printStack(Node* top) {
    Node* current = top;
    printf("Stack from top to bottom: ");
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

int main() {
    Node* stack = NULL;
    push(&stack, 1);
    push(&stack, 2);
    push(&stack, 3);
    printStack(stack);
    int top_element = peek(stack);
    if (top_element != -1) {
        printf("Top element is %d\n", top_element);
    }
    return 0;
}
new_node->next = *top_ref;
link new node to current top to keep stack order
*top_ref = new_node;
update top pointer to new node
if (top == NULL) {
check if stack is empty before peeking
return top->data;
return data of top element without removing
OutputSuccess
Stack from top to bottom: 3 2 1 Top element is 3
Complexity Analysis
Time: O(1) because peeking only reads the top element without traversal
Space: O(n) for n elements in stack due to linked nodes
vs Alternative: Compared to array-based stack, peek is also O(1), but linked list allows dynamic size without resizing
Edge Cases
empty stack
peek prints 'Stack is empty' and returns -1
DSA C
if (top == NULL) {
When to Use This Pattern
When you need to see the last added item without removing it, use the peek operation on a stack.
Common Mistakes
Mistake: Removing the top element instead of just peeking
Fix: Return the top element's data without changing the top pointer
Mistake: Not checking if stack is empty before peeking
Fix: Add a check for NULL top pointer before accessing data
Summary
Peek returns the top element of the stack without removing it.
Use peek when you want to know the current top value but keep the stack unchanged.
The key is to access the top node's data without modifying the stack structure.

Practice

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

Solution

  1. Step 1: Understand the peek operation

    The peek operation looks at the top element of the stack without changing the stack.
  2. Step 2: Compare with other stack operations

    Pop removes the top element, push adds an element, and isEmpty checks if stack is empty.
  3. Final Answer:

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

    Peek = top element without removal [OK]
Hint: Peek shows top without removing it [OK]
Common Mistakes:
  • Confusing peek with pop operation
  • Thinking peek removes the element
  • Mixing peek with push or isEmpty
2. Which of the following is the correct syntax to peek the top element of a stack named stack in C if top is the index of the top element and arr is the array storing stack elements?
easy
A. int x = arr[top - 1];
B. int x = arr[top + 1];
C. int x = arr[0];
D. int x = arr[top];

Solution

  1. Step 1: Understand stack top indexing

    Top points to the current top element index in the array.
  2. Step 2: Access the top element

    Accessing arr[top] gives the top element. Using top+1 or top-1 is incorrect as it points to wrong positions.
  3. Final Answer:

    int x = arr[top]; -> Option D
  4. Quick Check:

    Top index points to top element [OK]
Hint: Use arr[top] to peek top element [OK]
Common Mistakes:
  • Using top+1 or top-1 instead of top
  • Accessing arr[0] assuming stack bottom is top
  • Confusing top index with element value
3. What will be the output of the following C code snippet?
int stack[3] = {10, 20, 30};
int top = 2;
printf("%d", stack[top]);
medium
A. 10
B. 20
C. 30
D. Runtime error

Solution

  1. Step 1: Identify the top element index and stack contents

    Stack array has elements 10 at index 0, 20 at 1, and 30 at 2. Top is 2.
  2. Step 2: Access and print the top element

    stack[top] = stack[2] = 30, so printf prints 30.
  3. Final Answer:

    30 -> Option C
  4. Quick Check:

    stack[top] = 30 [OK]
Hint: Print stack[top] to get top element [OK]
Common Mistakes:
  • Confusing index 0 as top
  • Assuming top is out of range
  • Expecting pop removes element but code only prints
4. Find the error in this C code snippet that tries to peek the top element of a stack:
int stack[5] = {1, 2, 3, 4, 5};
int top = 4;
int peek() {
  return stack[top + 1];
}
medium
A. Accessing stack[top + 1] causes out-of-bounds error
B. top should be initialized to -1
C. Function should return void, not int
D. Stack array size is too small

Solution

  1. Step 1: Analyze the peek function access

    Peek returns stack[top + 1], which is stack[5] here (top=4), exceeding array size 5 (0-4).
  2. Step 2: Understand correct top indexing

    Top points to current top element, so peek should return stack[top], not stack[top + 1].
  3. Final Answer:

    Accessing stack[top + 1] causes out-of-bounds error -> Option A
  4. Quick Check:

    Index out of bounds error [OK]
Hint: Peek uses stack[top], not stack[top+1] [OK]
Common Mistakes:
  • Using top+1 instead of top for peek
  • Ignoring array bounds causing runtime error
  • Incorrect top initialization assumptions
5. Given a stack implemented using an array stack[5] and a variable top initialized to -1, which sequence of operations correctly peeks the top element after pushing 3 elements (10, 20, 30)?
hard
A. stack[++top] = 10; stack[++top] = 20; stack[++top] = 30; int x = stack[top];
B. stack[top] = 10; top = top + 1; stack[top] = 20; top = top + 1; stack[top] = 30; top = top + 1; int x = stack[top];
C. stack[top++] = 10; stack[top++] = 20; stack[top++] = 30; int x = stack[top];
D. top = 0; stack[top] = 10; top = 1; stack[top] = 20; top = 2; stack[top] = 30; int x = stack[top + 1];

Solution

  1. Step 1: Understand push operation with top

    Using stack[++top] = value increments top first, then assigns value, correctly pushing elements.
  2. Step 2: Peek top element after pushes

    After pushing 3 elements, top points to last pushed element. Accessing stack[top] gives top element.
  3. Final Answer:

    stack[++top] = 10; stack[++top] = 20; stack[++top] = 30; int x = stack[top]; -> Option A
  4. Quick Check:

    Push increments top, peek uses stack[top] [OK]
Hint: Use stack[++top] to push, stack[top] to peek [OK]
Common Mistakes:
  • Using post-increment top++ causing wrong indexing
  • Accessing stack[top + 1] for peek
  • Not initializing top to -1 before push
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