Complete the code to return the top element of the stack.
int peek(Stack *s) {
if (s->top == -1) {
return -1; // stack empty
}
return s->array[1];
}The top element is at index s->top in the array.
Complete the code to check if the stack is empty before peeking.
int peek(Stack *s) {
if ([1]) {
return -1; // stack empty
}
return s->array[s->top];
}The stack is empty when s->top is -1.
Fix the error in the peek function to correctly return the top element.
int peek(Stack *s) {
if (s->top == -1) {
return -1;
}
return s->array[1];
}s->top + 1 which is out of bounds.s->top - 1 which points to the wrong element.The top element is at index s->top. Using s->top + 1 or others is incorrect.
Fill both blanks to complete the peek function that returns the top element safely.
int peek(Stack *s) {
if ([1]) {
return -1;
}
return s->array[2];
}Check if stack is empty with s->top == -1 and return the element at s->array[s->top].
Fill all three blanks to implement a safe peek function that returns the top element or -1 if empty.
int peek(Stack *s) {
if ([1]) {
return [2];
}
return s->array[3];
}Check if stack is empty with s->top == -1, return -1 if empty, else return the top element at s->array[s->top].
