第十天| 232.用栈实现队列,225. 用队列实现栈
题目关键字:栈、队列
232_题目链接:https://leetcode.cn/problems/implement-queue-using-stacks/description/
代码实现
package LeetCode;
import com.sun.corba.se.spi.ior.ObjectKey;
import java.util.Stack;
public class YangSibo_232 {
public static void main (String args []) {
}
}
class MyQueue {
private Stack<Integer> stack = new Stack<>();
private Stack<Integer> tempstack = new Stack<>();
public MyQueue() {
}
public void push(int x) {
while (!stack.isEmpty()){
Integer tempnum = stack.peek();
stack.pop();
tempstack.push(tempnum);
}
stack.push(x);
while (!tempstack.isEmpty()){
Integer tempnum = tempstack.peek();
tempstack.pop();
stack.push(tempnum);
}
}
public int pop() {
return stack.pop();
}
public int peek() {
return stack.peek();
}
public boolean empty() {
if (stack.empty()){
return true;
}else {
return false;
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
解题注意事项:
1、stack无法获取长度,只能通过另外一个stack暂存数据
2、pop和push找对一个对上即可,修改另外一个
题目关键字:栈、队列
225_题目链接:https://leetcode.cn/problems/implement-stack-using-queues/
代码实现
package LeetCode;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class YangSibo_225 {
public static void main (String args []) {
}
}
class MyStack {
Queue<Integer> queue = new LinkedList<>();
public MyStack() {
}
public void push(int x) {
int circle = queue.size();
queue.add(x);
while (circle > 0) {
Integer temp = queue.peek();
queue.poll();
queue.add(temp);
circle--;
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
if (queue.isEmpty()) {
return true;
}else {
return false;
}
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
解题注意事项:
1、熟悉队列的属性及Queue的实例化方式
2、找出stack和queue的关键差异在数据插入方式以及队列可以获取长度