• 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();
        }
    }
  • 相关阅读:
    队列学哪个好
    python web 开发
    随笔
    问题集录
    大早晨地,快睡觉了,才想明白多线程代理验证是如何做的
    线程真的挺不错的,但是多了的时候也有点让人头痛
    愁死我了,写个控制台怎么好象在写解释器一样
    我越发地发现,我是在写一个解释器了
    哈哈,真有意思
    我要崩溃了。。。。
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11827334.html
Copyright © 2020-2023  润新知