Initial stack (empty):
+-----+
| | <- top (empty)
+-----+
After Push 10:
+-----+
| 10 | <- top
+-----+
After Push 20:
+-----+
| 20 | <- top
+-----+
| 10 |
+-----+
After Push 30:
+-----+
| 30 | <- top
+-----+
| 20 |
+-----+
| 10 |
+-----+
After Pop (remove 30):
+-----+
| 20 | <- top
+-----+
| 10 |
+-----+
After Push 40:
+-----+
| 40 | <- top
+-----+
| 20 |
+-----+
| 10 |
+-----+
This diagram shows the stack after each operation:
- Initial stack: The stack is empty.
- Push 10: 10 is added to the top.
- Push 20: 20 is added on top of 10.
- Push 30: 30 is added on top of 20.
- Pop: The top element 30 is removed, so 20 becomes the top.
- Push 40: 40 is added on top of 20.
The top of the stack is always the last item added that has not been removed, demonstrating the last-in, first-out (LIFO) principle.