当前位置: 代码迷 >> 综合 >> 232:用栈实现队列
  详细解决方案

232:用栈实现队列

热度:98   发布时间:2023-09-29 22:35:03.0

1:s1用来保证push的顺序,和empty操作

s2用来保证pop、peek操作

    Stack<Integer> s1 =new Stack<>();//push、emptyStack<Integer> s2 =new Stack<>();//pop、peekpublic MyQueue() {}public void push(int x) {s1.push(x);}public int pop() {//删除的时候先把s1装进s2,顺序就同队列了,删完装进s1while (!s1.isEmpty()){s2.push(s1.pop());}int a=s2.pop();while (!s2.isEmpty()){s1.push(s2.pop());}return a;}public int peek() {//删除的时候先把s1装进s2,顺序就同队列了,删完装进s1while (!s1.isEmpty()){s2.push(s1.pop());}int a=s2.peek();while (!s2.isEmpty()){s1.push(s2.pop());}return a;}public boolean empty() {return s1.isEmpty();}

2:下面这个s1和s2同1存储顺序相反,引入front标示s1里面第一个该删除的节点

    private Stack<Integer> s1 = new Stack<>();private Stack<Integer> s2 = new Stack<>();private Integer front;/** Initialize your data structure here. */public MYQueue2() {}/** Push element x to the back of queue. */public void push(int x) {if (s1.empty()){front = x;}while (!s1.isEmpty()){s2.push(s1.pop());}s2.push(x);while (!s2.isEmpty()){s1.push(s2.pop());}}/** Removes the element from in front of queue and returns that element. */public int pop() {int value = s1.pop();if (!s1.empty()){front = s1.peek();}return value;}/** Get the front element. */public int peek() {return front;}/** Returns whether the queue is empty. */public boolean empty() {return s1.isEmpty();}

3:入队出队都O(1)

    private Stack<Integer> s1 = new Stack<>();private Stack<Integer> s2 = new Stack<>();private Integer front;/** Initialize your data structure here. */public MyQueue3() {}/** Push element x to the back of queue. */public void push(int x) {if (s1.empty()){front = x;}s1.push(x);}/** Removes the element from in front of queue and returns that element. */public int pop() {if (s2.isEmpty()) {while (!s1.isEmpty()){s2.push(s1.pop());}}return s2.pop();}/** Get the front element. */public int peek() {if (!s2.isEmpty()) {return s2.peek();}return front;}/** Returns whether the queue is empty. */public boolean empty() {return s1.isEmpty() && s2.isEmpty();}

  相关解决方案