【leetcode】【225】Implement Stack using Queues

来源:互联网 发布:网络用语贼g2什么意思 编辑:程序博客网 时间:2024/05/23 00:09

一、问题描述

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.
Notes:
  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

二、问题分析

用Queues来实现stack,显然一个queue是完不成,因此可以采用两个queues。具体的操作可以看代码,并不难,无非就是两个队列相互的一些offer或者poll操作来完成stack的pop和push的功能。可以自己手动画一下。

三、Java AC代码

class MyStack {    private LinkedList<Integer> queue1 = new LinkedList<Integer>();private LinkedList<Integer> queue2 = new LinkedList<Integer>();    // Push element x onto stack.    public void push(int x) {        if (queue1.isEmpty()) {queue1.offer(x);while(!queue2.isEmpty()){queue1.offer(queue2.poll());}}else {queue2.offer(x);while(!queue1.isEmpty()){queue2.offer(queue1.poll());}}    }    // Removes the element on top of the stack.    public void pop() {        if (!queue1.isEmpty()) {queue1.poll();}else if (!queue2.isEmpty()){queue2.poll();}    }    // Get the top element.    public int top() {    if (!queue1.isEmpty()) {return queue1.peek();}else {return queue2.peek();}    }    // Return whether the stack is empty.    public boolean empty() {        return queue1.isEmpty()&&queue2.isEmpty();    }}


0 0
原创粉丝点击