[LintCode] 用栈实现队列
1 class Queue { 2 public: 3 stack<int> stack1; 4 stack<int> stack2; 5 6 Queue() { 7 // do intialization if necessary 8 } 9 10 void push(int element) { 11 // write your code here 12 stack1.push(element); 13 } 14 15 int pop() { 16 // write your code here 17 if (stack2.empty()) { 18 while (!stack1.empty()) { 19 int elem = stack1.top(); 20 stack1.pop(); 21 stack2.push(elem); 22 } 23 } 24 int elem = stack2.top(); 25 stack2.pop(); 26 return elem; 27 } 28 29 int top() { 30 // write your code here 31 if (stack2.empty()) { 32 while (!stack1.empty()) { 33 int elem = stack1.top(); 34 stack1.pop(); 35 stack2.push(elem); 36 } 37 } 38 return stack2.top(); 39 } 40 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步