zoukankan      html  css  js  c++  java
  • [leetcode] 225. 用队列实现栈

    LeetCode.225 用队列实现栈

    栈pop的时候将当前队列的处最后一个元素之外的所有元素出队到另外一个元素里,然后出队最后一个元素即可

    public class MyStack {
    
    	List<Integer> first;
    	List<Integer> second;
    
    	/**
    	 * Initialize your data structure here.
    	 */
    	public MyStack() {
    		first = new ArrayList<Integer>();
    		second = new ArrayList<Integer>();
    	}
    
    	/**
    	 * Push element x onto stack.
    	 */
    	public void push(int x) {
    		first.add(x);
    	}
    
    	/**
    	 * Removes the element on top of the stack and returns that element.
    	 */
    	public int pop() {
    		while (!first.isEmpty()) {
    			second.add(first.get(0));
    			first.remove(0);
    		}
    
    		Integer integer = second.get(second.size() - 1);
    		second.remove(second.size() - 1);
    
    		return integer;
    	}
    
    	/**
    	 * Get the top element.
    	 */
    	public int top() {
    		while (!first.isEmpty()) {
    			second.add(first.get(0));
    			first.remove(0);
    		}
    
    		Integer integer = second.get(second.size() - 1);
    
    		return integer;
    	}
    
    	/**
    	 * Returns whether the stack is empty.
    	 */
    	public boolean empty() {
    		return first.isEmpty() && second.isEmpty();
    	}
    }
    
  • 相关阅读:
    GeoServer发布PostGIS数据库中的栅格数据
    CMD查看端口占用情况
    css选择器命名推荐
    css书写顺序
    css中浮动相关
    动态规划算法
    KMP算法 字符串匹配
    Java 反射
    分治(Divide-and-Conquer(P))算法
    图 结构
  • 原文地址:https://www.cnblogs.com/acbingo/p/10285573.html
Copyright © 2011-2022 走看看