zoukankan      html  css  js  c++  java
  • 剑指offer【05】 用两个栈实现队列(java)

    题目:用两个栈实现队列

    考点:栈和队列

    题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

    解题思路:每次psuh是时先将stack2清空放入stck1(保证选入的一定在栈底),stack2始终是用来删除的。在pop前,先将stack1中中的数据清空放入stack2(保存后入的在栈底),stack1始终用于push。

     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         //向stack2 push时,先判断Stack2是否为空,
     9         //如果不为空则将stack2的元素出栈,放进stack1中
    10         while(!stack2.isEmpty()){
    11              stack1.push(stack2.pop());
    12         }
    13         //stack2为空,则直接放入元素
    14         stack2.push(node);
    15     }
    16     
    17     public int pop() {
    18         //栈2元素出栈时先判断栈1是否为空
    19         //如果不为空则将stack1的元素出栈,放进stack2中
    20         while(!stack1.isEmpty()){
    21             stack2.push(stack1.pop());
    22         }
    23         //栈1为空,此时栈2直接出栈
    24         return stack2.pop();
    25     }
    26 }
  • 相关阅读:
    Windows XP SP1 Privilege Escalation
    A way escape rbash
    A trick in Exploit Dev
    wget.vbs & wget.ps1
    IDEA创建普通java和web项目教程
    初始Mybatis
    JAVA高级面试题
    JVM执行原理
    java-- 位运算
    JAVA---XML
  • 原文地址:https://www.cnblogs.com/linliquan/p/10585694.html
Copyright © 2011-2022 走看看