剑指offer——用两个栈实现队列
生活随笔
收集整理的這篇文章主要介紹了
剑指offer——用两个栈实现队列
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目:用兩個棧來實現(xiàn)一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。
?
解題思路:
?
當stack2不為空時,在stack2中的棧頂元素是最先進入隊列的元素,可以彈出。當stack2為空時,我們把stack1中的元素逐個彈出并壓入stack2.由于先進入隊列的元素被壓到stack1,底端,經(jīng)過彈出和壓入操作后就處于stack2的頂端。
1 import java.util.Stack; 2 3 public class Solution { 4 Stack<Integer> stack1 = new Stack<Integer>(); 5 Stack<Integer> stack2 = new Stack<Integer>(); 6 7 public void push(int node) { 8 stack1.push(node); 9 } 10 11 public int pop() { 12 if(stack2.empty())//如果stack2不為空,不可以push 13 { 14 while(!stack1.empty()) 15 stack2.push(stack1.pop()); 16 17 } 18 return stack2.pop(); 19 20 } 21 }?
轉載于:https://www.cnblogs.com/wangyufeiaichiyu/p/10844442.html
總結
以上是生活随笔為你收集整理的剑指offer——用两个栈实现队列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: search engine php,用p
- 下一篇: 百度文库免费下载文档方法