所用代码 java
用栈实现队列 LeecCode 232
题目链接:用栈实现队列 LeecCode 232 - 简单
思路
使用两个栈,一个stack负责放数据,一个stack负责取数据
Stack<Integer> stackPut;
Stack<Integer> stackGet;
public MyQueue() {
stackPut = new Stack<>();
stackGet = new Stack<>();
}
public void push(int x) {
stackPut.push(x);
}
public int pop() {
PutToGet();
return stackGet.pop();
}
public int peek() {
PutToGet();
return stackGet.peek();
}
public boolean empty() {
if (stackGet.empty() && stackPut.empty()){
return true;
}else {
return false;
}
}
public void PutToGet(){
// 如果stackGet为空,就不用往stackGet里放数据
if (!stackGet.isEmpty()) return;
while (!stackPut.empty()){
// 否则把stackPut的所有元素存到stackGet
stackGet.push(stackPut.pop());
}
}
总结
关键在于PutToGet()函数,只有在stack2不为空的时候再往里放数据,否则就和普通的栈没区别了。
用队列实现栈 LeetCode 225
题目链接:用队列实现栈 LeetCode 225 - 简单
思路
单向链表
Queue<Integer> queue;
Queue<Integer> temp;
public MyStack() {
queue = new LinkedList<>();
temp = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
}
public int pop() {
adjust();
return queue.poll();
}
public int top() {
adjust();
int top = queue.peek();
temp.offer(queue.poll());
queue.offer(temp.poll());
return top;
}
public boolean empty() {
return 0 == queue.size();
}
// 用于调整到链表最后一个元素处于起始位置
public void adjust(){
int size = queue.size();
if (size == 0) return;
for (int i = 0; i < size - 1; i++) {
// temp 用来临时接受queue弹出的值
temp.offer(queue.poll());
// queue把弹出的值放在队列尾部
queue.offer(temp.poll());
}
}
双向链表
// 用双向链表太简单了
Deque<Integer> deque;
public MyStack() {
deque = new ArrayDeque<>();
}
public void push(int x) {
deque.offerLast(x);
}
public int pop() {
return deque.pollLast();
}
public int top() {
return deque.peekLast();
}
public boolean empty() {
return 0 == deque.size();
}
总结
可以看到双向链表操作非常的简单,所有在java里面都不太愿意直接使用Stack了,因为双向链表就可以直接模拟和队列。
ps:今天的题比较简单,只要熟悉栈和队列的基本操作都能做!