Bird
0
0
DSA Cprogramming~10 mins

Peek Top Element of Stack in DSA C - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return the top element of the stack.

DSA C
int peek(Stack *s) {
    if (s->top == -1) {
        return -1; // stack empty
    }
    return s->array[1];
}
Drag options to blanks, or click blank then click option'
A[top]
B[s->top]
C[s->top - 1]
D[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong index like 0 or top-1.
Trying to access a variable named 'top' instead of s->top.
2fill in blank
medium

Complete the code to check if the stack is empty before peeking.

DSA C
int peek(Stack *s) {
    if ([1]) {
        return -1; // stack empty
    }
    return s->array[s->top];
}
Drag options to blanks, or click blank then click option'
As->top == -1
Bs->top == 0
Cs->top > 0
Ds->top < 0
Attempts:
3 left
💡 Hint
Common Mistakes
Checking if top is 0 instead of -1.
Using greater than or less than comparisons incorrectly.
3fill in blank
hard

Fix the error in the peek function to correctly return the top element.

DSA C
int peek(Stack *s) {
    if (s->top == -1) {
        return -1;
    }
    return s->array[1];
}
Drag options to blanks, or click blank then click option'
A[s->top + 1]
B[0]
C[s->top - 1]
D[s->top]
Attempts:
3 left
💡 Hint
Common Mistakes
Using s->top + 1 which is out of bounds.
Using s->top - 1 which points to the wrong element.
4fill in blank
hard

Fill both blanks to complete the peek function that returns the top element safely.

DSA C
int peek(Stack *s) {
    if ([1]) {
        return -1;
    }
    return s->array[2];
}
Drag options to blanks, or click blank then click option'
As->top == -1
Bs->top == 0
C[s->top]
D[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Checking wrong condition for empty stack.
Accessing array at wrong index.
5fill in blank
hard

Fill all three blanks to implement a safe peek function that returns the top element or -1 if empty.

DSA C
int peek(Stack *s) {
    if ([1]) {
        return [2];
    }
    return s->array[3];
}
Drag options to blanks, or click blank then click option'
As->top == -1
B-1
C[s->top]
Ds->top == 0
Attempts:
3 left
💡 Hint
Common Mistakes
Returning wrong value when empty.
Accessing array at wrong index.