zoukankan      html  css  js  c++  java
  • 剑指offer

    五、栈和队列

    1. 用两个栈来实现队列

    题目描述:

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

    思路:

    入队:stack1入栈。

    出队:若stack2非空,则stack2弹出栈顶元素;若stack2为空,且stack1非空,则将stack1中的元素全部压入stack2中,然后弹出stack2的栈顶元素。

    代码:

    import java.util.Stack;
    
    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        
        public void push(int node) {
            stack1.push(node);
        }
        
        public int pop() {
            if (stack2.isEmpty() && !stack1.isEmpty()) {
                while (!stack1.isEmpty()) {
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();
        }
    }
    
  • 相关阅读:
    (转)IDEA ERROR:找不到或无法加载主类
    Piggy-Bank
    Monkey and Banana
    Max Sum Plus Plus
    Doing Homework
    繁繁的游戏
    看试卷
    繁繁的队列
    大整数乘法
    文件操作(c++)
  • 原文地址:https://www.cnblogs.com/jiajun107/p/12488325.html
Copyright © 2011-2022 走看看