目录
题目1: 232.用栈实现队列
- 题目链接:232. 用栈实现队列
1- 思路
基础:栈在Java中的常见操作及API
栈是一种后进先出(LIFO)的数据结构。Java中的Stack类继承自Vector类,提供了以下常用方法:
push(E item)
:把项压入堆栈顶部。pop()
: 移除堆栈顶部的对象,并作为此函数的值返回该对象。peek()
:查看堆栈顶部的对象,但不从堆栈中移除它。isEmpty()
:判断栈是否为空
基础:队列在Java中的常见操作及API
队列是一种先进先出(FIFO)的数据结构。Java中的Queue接口定义了以下常用方法:
offer(E e)
:添加元素到队列中,若添加成功则返回 true,若队列已满则返回 falsepoll()
:移除队列头的元素,若此时队列为空,则返回 nullpeek()
:peek()方法用于查看队列头部的元素,但不会从队列中移除这个元素。isEmpty()
:判断队列是否为空
用两个栈实现队列
- 定义两个栈,将一个栈定义为 inStack,一个栈为 outStack,若发生了队列的 poll() 操作,则需要将 inStack的所有元素压入到 outStack 中此时便能实现 队列的先进先出操作。
2- 题解
⭐用栈实现队列 ——题解思路
class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue() {
inStack = new Stack<>();
outStack = new Stack<>();
}
public void push(int x) {
// 队列的 push 操作
inStack.push(x);
}
public int pop() {
dumpstackIn();
return outStack.pop();
}
public int peek() {
dumpstackIn();
return outStack.peek();
}
public boolean empty() {
return inStack.isEmpty()&&outStack.isEmpty();
}
// 如果 outStack 为空,将 inStack的内容全放进 outStack
private void dumpstackIn(){
if(!outStack.isEmpty()) return;
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
}
题目2: 225. 用队列实现栈
- 题目链接:225. 用队列实现栈
1- 思路
用一个队列实现栈
- 用一个队列实现栈的思路在于,如果涉及到弹出元素,则只需要将 队列长度 n-1 前的元素重新加入队列,此时弹出的元素就是最后加入的元素
①push实现
- 栈的 push 也就是队列的 push
②pop实现
- 首先需要获取队列的 size,size自减少
- 并将 size-1 的元素弹出重加回到队列中
- 之后执行队列的 poll() 取出第一个元素即可
③Top实现
- 找到 队列的 last
2- 题解
⭐用栈实现队列 ——题解思路
class MyStack {
Queue<Integer> queue ;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
// 压入元素
queue.offer(x);
}
// 弹出
public int pop() {
transToLast();
return queue.poll();
}
public int top() {
transToLast();
int res = queue.poll();
queue.add(res);
return res;
}
public boolean empty() {
return queue.isEmpty();
}
private void transToLast(){
int size = queue.size();
for(int i = 0 ; i < size-1;i++){
queue.offer(queue.poll());
}
}
}