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();
    		
    	}
    
    }
    
    
  • 相关阅读:
    JVM的即时编译器JIT之简单介绍
    JS脚本动态给标签控件添加事件
    getParameterMap的使用
    IOS开发中判断文件是否存在,不存在则拷贝
    javaweb中解决Cookie中文乱码问题
    网页中的上标和下标实现
    Java中枚举的使用
    ASP.NET 首页性能的4大做法
    httpHandlers和httpModules接口介绍 (5)
    css+div排版如何支持所有浏览器
  • 原文地址:https://www.cnblogs.com/nmydt/p/14256380.html
Copyright © 2011-2022 走看看