单选题
适中
#13039
以下代码的输出是?( ) stack<int> st; for (int i=1; i<=3; i++) st.push(i); while (!st.empt…
以下代码的输出是?( )
stack<int> st;
for (int i=1; i<=3; i++) st.push(i);
while (!st.empty()) {
cout << st.top() << " ";
st.pop();
}
答案与解析
正确答案:B
解析
for循环依次把1、2、3压入栈st,此时栈为:1 2 3, 栈底 1,栈顶 3。
栈的特点是后进先出,在while循环中,依次弹出栈顶:3 2 1,输出并删除栈顶元素。