Concept Flow - Peek Top Element of Stack
Start
Check if stack is empty?
Yes→Return error or NULL
No
Access top element
Return top element
End
The flow checks if the stack is empty. If not, it accesses and returns the top element without removing it.
int peek(Stack* s) { if (s->top == -1) return -1; // empty return s->arr[s->top]; }
| Step | Operation | Stack Top Index | Stack Array | Pointer Changes | Visual State |
|---|---|---|---|---|---|
| 1 | Start peek operation | 2 | [10, 20, 30] | top points to index 2 | 30 (top) -> 20 -> 10 -> null |
| 2 | Check if stack is empty (top == -1?) | 2 | [10, 20, 30] | No change | 30 (top) -> 20 -> 10 -> null |
| 3 | Access element at top index | 2 | [10, 20, 30] | No change | 30 (top) -> 20 -> 10 -> null |
| 4 | Return top element (30) | 2 | [10, 20, 30] | No change | 30 (top) -> 20 -> 10 -> null |
| 5 | End peek operation | 2 | [10, 20, 30] | No change | 30 (top) -> 20 -> 10 -> null |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| top | 2 | 2 | 2 | 2 | 2 |
| stack array | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] |
| peeked value | N/A | N/A | N/A | 30 | 30 |
Peek Top Element of Stack: - Check if stack is empty (top == -1) - If empty, return error or special value - Else, return element at stack[top] - Does NOT remove element - Stack remains unchanged after peek
peek operation do in a stack?stack in C if top is the index of the top element and arr is the array storing stack elements?int stack[3] = {10, 20, 30};
int top = 2;
printf("%d", stack[top]);int stack[5] = {1, 2, 3, 4, 5};
int top = 4;
int peek() {
return stack[top + 1];
}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)?Pass the test and this pattern moves unknown