栈和队列的相互实现

用栈实现队列

题目

题目地址:https://leetcode-cn.com/problems/implement-queue-using-stacks/

使用栈实现队列的下列操作:

push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
示例:

1
2
3
4
5
6
7
MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.jarome.leetcode.test1.summary;

import java.util.Stack;

public class MyQueue {

Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();

/** Initialize your data structure here. */
public MyQueue() {
}

/** Push element x to the back of queue. */
public void push(int 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() {
return s1.pop();
}

/** Get the front element. */
public int peek() {
return s1.peek();
}

/** Returns whether the queue is empty. */
public boolean empty() {
return s1.isEmpty();
}

}

用队列实现栈

题目

题目地址:https://leetcode-cn.com/problems/implement-stack-using-queues/

使用队列实现栈的下列操作:

push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.jarome.leetcode.test1.summary;

import java.util.LinkedList;
import java.util.Queue;

class MyStack {

Queue<Integer> q1 = new LinkedList<>();
Queue<Integer> q2 = new LinkedList<>();

/** Initialize your data structure here. */
public MyStack() {}

/** Push element x onto stack. */
public void push(int x) {
q2.offer(x);
while (!q1.isEmpty())
q2.offer(q1.poll());
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.poll();
}

/** Get the top element. */
public int top() {
return q1.peek();
}

/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}