225. Implement Stack using Queues

来源:互联网 发布:js日期格式化yyyymmdd 编辑:程序博客网 时间:2024/06/06 01:22

225. Implement Stack using Queues

使用两个队列实现栈,思路:

  • q1为入队列提供压栈功能,q2为出队列提供出栈功能
  • 要压栈,入队列q1即可,当出栈时,分两种情况:
    • 若队列q1中只有一个元素,则让q1中的元素出队列并输出
    • 若队列q1中不只一个元素,则队列q1中所有元素出队列,入队列q2,最后一个元素不入队列q2,输出钙元素,然后将队列q2所有元素入队列q1

实现代码:

import java.util.LinkedList;import java.util.Queue;public class MyStack {    Queue<Integer> q1 = new LinkedList<>();    // 为什么使用LinkedList见下面解释    Queue<Integer> q2 = new LinkedList<>();    /** Initialize your data structure here. */    public MyStack() {    }    /** Push element x onto stack. */    public void push(int x) {        q1.offer(x);    }    /** Removes the element on top of the stack and returns that element. */    public int pop() {        if(q1.isEmpty()) return 0;        else{            while (q1.size() > 1){                q2.offer(q1.poll());            }            int last = q1.poll();          //对于已经出现返回值还要后续操作的,可以先保存            Queue<Integer> q = q2;              q2 = q1;              q1 = q;            return last;        }   }     /** Get the top element. */    public int top() {        if(q1.size() == 0) return 0;          while(q1.size() > 1){              q2.offer(q1.poll());          }          int top = q1.peek();          q2.offer(q1.poll());     // 不需要删除,所以最后一个还是要入队列的        Queue<Integer> q = q2;          q2 = q1;          q1 = q;          return top;      }      /** Returns whether the stack is empty. */    public boolean empty() {        return q1.isEmpty() && q2.isEmpty();    }}

注释1:LinkedList类实现了Deque(双端队列)接口,Deque又继承自Queue接口,因此可以使用LinkedList创建一个队列。LinkedList很适合用于进行队列操作,因为它可以高效在线性表的两端插入和移除元素。

0 0
原创粉丝点击