• [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();
    	}
    }
    
  • 相关阅读:
    由二进制移位想到的
    KDJ指标详解
    PMP考试结束
    转K线理论初级二
    日本地震效应
    Baseline之流水先生的见解
    KDJ判断原则
    转K线理论初级一
    管理学法则
    今天提到KW,特此@Mark一下
  • 原文地址:https://www.cnblogs.com/acbingo/p/10285573.html
Copyright © 2020-2023  润新知