zoukankan      html  css  js  c++  java
  • 11/9 <Stack> 155 232 225

    155. Min Stack

    class MinStack {
        int min = Integer.MAX_VALUE;
        Stack<Integer> stack = new Stack<Integer>();
        /** initialize your data structure here. */
        public MinStack() {
            
        }
        
        public void push(int x) {
            if(x <= min){
                stack.push(min);
                min = x;
            }
            stack.push(x);
        }
        
        public void pop() {
            if(stack.pop() == min) min = stack.pop();
        }
        
        public int top() {
            return stack.peek();
        }
        
        public int getMin() {
            return min;
        }
    }

    232. Implement Queue using Stacks

    用一个input和outlput栈,当pop时,output为空,则把input全部压入output中。

    class MyQueue {
        Stack<Integer> input = new Stack();
        Stack<Integer> output = new Stack();
        /** Initialize your data structure here. */
        public MyQueue() {
            
        }
        
        /** Push element x to the back of queue. */
        public void push(int x) {
            input.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        public int pop() {
            peek();
            return output.pop();
        }
        
        /** Get the front element. */
        public int peek() {
            if(output.empty())
                while(!input.empty())
                    output.push(input.pop());
            return output.peek();
        }
        
        /** Returns whether the queue is empty. */
        public boolean empty() {
            return input.empty() && output.empty();
        }
    }

    225. Implement Stack using Queues

    在push的时候就直接把顺序缓过来

    class MyStack {
        Queue<Integer> queue;
        /** Initialize your data structure here. */
        public MyStack() {
            this.queue = new LinkedList<Integer>();
        }
        
        /** Push element x onto stack. */
        public void push(int x) {
            queue.add(x);
            for(int i = 0; i < queue.size() - 1; i++){
                queue.add(queue.poll());
            }
        }
        
        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            return queue.poll();
        }
        
        /** Get the top element. */
        public int top() {
            return queue.peek();
        }
        
        /** Returns whether the stack is empty. */
        public boolean empty() {
            return queue.isEmpty();
        }
    }
  • 相关阅读:
    C#生成MD5的方法
    平常心是道
    Android 三种动画的使用 – Tween Animation
    17个Javascript日期选择器
    Javascript解码编码常用函数
    mysql 命令行导入导出数据
    技术驱动还是产品驱动
    Ubuntu 和 Redhat / Fedora 服务管理命令对比表
    jquery常用技巧
    Fedora 17安装JDK1.7
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11827334.html
Copyright © 2011-2022 走看看