Stack Simulation: Implement Push, Pop, Query, and Empty Operations
Problem Description
We need to implement a stack that starts empty and supports four core operations:
push x– Insert the number x at the top of the stack;pop– Remove the element from the top of the stack;empty– Check if the stack is empty; output "YES" if it is, otherwise "NO";query– Retrieve and output the value of the top element of the stack.
We will process a total of M operations. For every empty or query command, we must output the corresponding result.
Input Format
The first line contains an integer M, representing the number of operations to perform.
Each of the next M lines contains one valid operation command from the set push x, pop, empty, query.
Output Format
For each empty operation, print "YES" if the stack is empty, or "NO" if it is not.
For each query operation, print the integer value of the stack's top element.
Each output result must be on a separate line.
Data Constraints
- 1 ≤ M ≤ 100,000
- 1 ≤ x ≤ 10^9
- All operations are guaranteed to be valid (e.g., no
popcommands will be issued on an empty stack).
Input Example
10
push 5
query
push 6
pop
query
pop
empty
push 4
query
empty
Output Example
5
5
YES
4
NO
Implementation Code
#include <iostream>
#include <string>
using namespace std;
const int MAX_STACK_SIZE = 100010;
int stack_buffer[MAX_STACK_SIZE];
int top_index = 0;
int main() {
// Optimize input/output speed for large datasets
ios::sync_with_stdio(false);
cin.tie(nullptr);
int operation_count;
cin >> operation_count;
while (operation_count--) {
string command;
cin >> command;
if (command == "push") {
int val;
cin >> val;
stack_buffer[++top_index] = val;
} else if (command == "pop") {
top_index--;
} else if (command == "empty") {
cout << (top_index == 0 ? "YES" : "NO") << '\n';
} else if (command == "query") {
cout << stack_buffer[top_index] << '\n';
}
}
return 0;
}
Code Explanations
- Stack Storage: We use a fixed-size array
stack_bufferto store stack elements, with a maximum size of 100010 to accommodate up to 100,000 operatiosn. - Top Index Management:
top_indextracks the position of the top element in the array. We use 1-based indexing for simplicity (sostack_buffer[1]is the first element pushed,stack_buffer[top_index]is the current top). - Input Optimization: The lines
ios::sync_with_stdio(false);andcin.tie(nullptr);disible synchronization with C standard I/O functions and untie cin from cout, significantly speeding up input handling for large numbers of operations. - Ternary Operator: The condition
top_index == 0 ? "YES" : "NO"efficiently checks if the stack is empty. Iftop_indexis 0, the stack has no elements (output YES), otherwise it's non-empty (output NO). - Efficient Output: Using
'\n'instead ofendlavoids unnecessary buffer flushes, which improves performance for large output volumes.