用栈实现队列

入队
图片.png
出队
图片.png

232. 用栈实现队列

图片.png

  1. class MyQueue {
  2. LinkedList<Integer> st1;
  3. LinkedList<Integer> st2;
  4. public MyQueue() {
  5. st1=new LinkedList<>();//出队用的栈
  6. st2=new LinkedList<>();//入队用的栈
  7. }
  8. public void push(int x) {
  9. st2.push(x);
  10. }
  11. public int pop() {
  12. peek();//防止st1中没有元素 先进行一个peek()操作
  13. return st1.pop();
  14. }
  15. public int peek() {
  16. if(st1.isEmpty())//如果出队的栈中没有元素了 开始将入队栈中的元素加入出队栈
  17. {
  18. while(!st2.isEmpty())
  19. st1.push(st2.pop());
  20. }
  21. return st1.peek();//返回队首元素
  22. }
  23. public boolean empty() {
  24. return st1.isEmpty()&&st2.isEmpty();//两个栈同时为空
  25. }
  26. }

用队列实现栈

图片.png

225. 用队列实现栈

class MyStack {
    Queue<Integer> q1;
    Queue<Integer> q2;
    public MyStack() {
        q1=new LinkedList<>();
        q2=new LinkedList<>();
    }

    public void push(int x) {
        q2.offer(x);
        //循环结束之后q1为空
        while(!q1.isEmpty())
        {
            q2.offer(q1.poll());
        }
        //交换之后q2为空
        Queue tmp=q1;
        q1=q2;
        q2=tmp;

    }
    //下面的操作始终使用q1
    public int pop() {
        return q1.poll();

    }

    public int top() {
        return q1.peek();

    }

    public boolean empty() {
        return q1.isEmpty();

    }
}