zoukankan      html  css  js  c++  java
  • LeetCode 225. 用队列实现栈 做题笔记

    题目:

    使用队列实现栈的下列操作:

    push(x) – 元素 x 入栈
    pop() – 移除栈顶元素
    top() – 获取栈顶元素
    empty() – 返回栈是否为空
    注意:

    你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
    你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
    你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

    题解:

    使用一个队列实现栈的操作

    使用一个队列时,为了满足栈的特性,即最后入栈的元素最先出栈,同样需要满足队列前端的元素是最后入栈的元素。

    入栈操作时,首先获得入栈前的元素个数 n,然后将元素入队到队列,再将队列中的前 n 个元素(即除了新入栈的元素之外的全部元素)依次出队并入队到队列,此时队列的前端的元素即为新入栈的元素,且队列的前端和后端分别对应栈顶和栈底。

    由于每次入栈操作都确保队列的前端元素为栈顶元素,因此出栈操作和获得栈顶元素操作都可以简单实现。出栈操作只需要移除队列的前端元素并返回即可,获得栈顶元素操作只需要获得队列的前端元素并返回即可(不移除元素)。

    由于队列用于存储栈内的元素,判断栈是否为空时,只需要判断队列是否为空即可。

    代码:

    import java.util.LinkedList;
    import java.util.Queue;
    
    public class queuetostack {
    	Queue<Integer> queue;
    
        /** Initialize your data structure here. */
        public queuetostack() {
            queue = new LinkedList<Integer>();
        }
        
        /** Push element x onto stack. */
        public void push(int x) {
            int n = queue.size();
            queue.add(x);
            for (int i = 0; i < n; 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();
        }
        public void print() {
        	System.out.println(Arrays.toString(queue.toArray()));
        }
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		queuetostack aQueuetostack = new queuetostack();
    		aQueuetostack.push(3);
    		aQueuetostack.push(4);
    		aQueuetostack.pop();
    		//System.out.println(aQueuetostack.top());
    		System.out.println(aQueuetostack.top());
    		aQueuetostack.print();
    		
    	}
    
    }
    
    
  • 相关阅读:
    Direct2D教程(二)来看D2D世界中的Hello,World
    绕任意轴旋转
    XPDM vs WDDM
    也谈杨辉三角形
    用DirectX实现粒子系统(一)
    Alpha混合(一)Vertex Alpha
    几何变换详解
    用DirectX实现粒子系统(三)
    Alpha混合(二)Material Alpha
    Direct2D教程(五)复合图形
  • 原文地址:https://www.cnblogs.com/nmydt/p/14256380.html
Copyright © 2011-2022 走看看