中缀表达书转后缀表达式(不带括号)
1、碰见优先级比栈顶运算符高的运算符入栈,
2、否则把栈内优先级>=它的都出栈,它再入栈,
3、遍历完成,栈内剩余运算符依次出栈
(带括号)1、左括号直接入栈,碰见右括号直接出栈,出栈到括号结束;
232. 用栈实现队列 - 力扣(LeetCode)
package Test01;
import java.util.LinkedList;
class MyQueue {
LinkedList<Integer> s1=new LinkedList<>();//继承queue接口
LinkedList<Integer> s2=new LinkedList<>();
public MyQueue() {
}
public void push(int x) {
s2.push(x);
}
public int pop() {
if(s1.isEmpty()){
while(!s2.isEmpty()){
s1.push(s2.pop());
}
}
return s1.pop();//注意:想要移除元素
}
public int peek() {
if(s1.isEmpty()){
while(!s2.isEmpty()){
s1.push(s2.pop());
}
}
return s1.peek();//不需要移除元素
}
public boolean empty() {
return s1.isEmpty()&&s2.isEmpty();//特别注意:想要判断两个栈都为空才能确定整个队列为空
}
}
/**
* 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();
*/
225. 用队列实现栈 - 力扣(LeetCode)
class MyStack {
LinkedList<Integer> queue=new LinkedList<>();
private int size;
public MyStack() {
}
public void push(int x) {
queue.offer(x);
for(int i=0;i<size;i++){
queue.offer(queue.poll());//将队列头的元素移到队列尾
}
size++;
}
public int pop() {
size--;
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}
/**
* 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、迭代器遍历
2、添加头部和尾部
3、删除头部和尾部
堆实现
堆的特性如图:
完全二叉树:除了最后一层,每层都是填满的(最后一层从左到右依次填)最后一层也可以填满;
左孩子索引:
从0开始,节点i的父节点为floor((i-1)/2),当且仅当i>0;左孩子节点为2i+1,右孩子节点为2i+2;
从1开始,节点i的父节点为floor(i/2),当且仅当i>1,孩子左节点为2i,右孩子节点为2i+1;