#include <stdio.h>
#include <stack>
using namespace std;
int solve(stack<int> &st,int k) //出栈第 k 个元素
{ stack<int> tmpst; int e; for (int i=0;i<k;i++) //出栈 st 的 k 个元素并进 tmpst 栈
{ e=st.top(); st.pop(); tmpst.push(e); }
e=tmpst.top(); //求第 k 个元素
tmpst.pop();
while (!tmpst.empty()) //将 tmpst 的所有元素出栈并进栈 st
{ st.push(tmpst.top());
tmpst.pop();
}
return e; }
void disp(stack<int> &st) //出栈 st 的所有元素
{ while (!st.empty())
{ printf("%d ",st.top()); st.pop();
} printf("\n"); } void main()
{ stack<int> st;
printf("进栈元素 1,2,3,4\n");
st.push(1); st.push(2); st.push(3); st.push(4); int k=3;
int e=solve(st,k); printf("出栈第%d 个元素是: %d\n",k,e);
printf("st 中元素出栈顺序: ");
disp(st);
}
温馨提示:答案为网友推荐,仅供参考