1.用两个栈实现队列
import java.util.Stack;
public class Solution{
Stack<Integer> stack1=new Stack<Integer>();
Stack<Integer> stack2=new Stack<Integer>();
public void push(int node){
stack1.push(node);
}
public int pop() throws Exception{
if(stack1.isEmpty()&&stack2.isEmpty()){
throw new Exception("栈为空!");
}
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
思路:1.push操作就直接往stack1中push.
2.pop操作需要分类:如果stack2为空,那么需要将stack1中的数据转移到stack2中,然后对stack2进行pop.
3.如果stack2不为空,直接pop就ok.
2.包含main函数的栈
import java.util.Stack;
public class Solution{
private static Stack<Integer> stack=new Stack<Integer>();
private static Integer minElement=Integer.MAX_VALUE;
public void push(int node){
if(stack.empty()){
minElement=node;
stack.push(node);
}else{
if(node<=minElement){
stack.push(minElement);
minElement=node;
}
stack.push(node);
}
}
public void pop(){
if(stack.size()==0) return;
if(minElement==stack.peek()){
if(stack.size()>1){
stack.pop();
minElement=stack.peek();
}else{
minElement=Integer.MAX_VALUE;
}
}
stack.pop();
}
public int top(){
return stack.peek();
}
public int min(){
return minElement;
}
}
思路:pop的时候判断两个栈顶元素是否一致,一致的话要pop,在这种情况下取最小值需要从保存最小值得栈顶元素取值。
1.往栈中压入值得时候,如果栈为空,那就直接压入,并为最小值;
如果有值,并且比压入的值还小,那就继续压入,并把最小值更新为之前的值
3.栈的压入、弹出序列
import java.util.ArrayList;
import java.util.Stack;
public class Solution{
public boolean IsPopOrder(int [] pushA,int [] popA){
if(pushA==null||popA==null){
return false;
}
Stack<Integer> stack=new Stack<>();
int index=0;
for(int i=0;i<pushA.lenght;i++){
stack.push(pushA[i]);
while(!stack.isEmpty()&&stack.peek()==popA[index]){
stack.pop();
index++;
}
}
return stack.isEmpty();
}
}
思路:1.新建一个栈,将数组A压入栈中
2.当栈顶元素等于数组B时,就将其出栈。
3.当循环结束时,判断栈是否为空,若为空则返回true.
4.从上往下打印二叉树
import java.util.ArrayList;
public class Solution{
public ArrayList<Integer> PrintFormTopToBottom(TreeNode root){
ArrayList<Integer> list=new ArrayList<Integer>();
if(root==null){
return list;
}
list.add(root.val);
levelOrder(root,list);
return list;
}
public void levelOrder(TreeNode root,ArrayList<Integer> list){
if(root==null){return;}
if(root.left!=null){
list.add(root.left.val);
}
if(root.right!=null){
list.add(root.right.val);
}
levelOrder(root.left,list);
levelOrder(root.right,list);
}
}
思路:1.创建一个list集合。
2.先打印根节点。如果该节点有子节点,就把该节点的子节点放到一个队列的尾部
3.接下来到队列的头部取出最早进入队列的节点放到ArrayList中。重复前面的操作,直至队列中所有的节点度存到ArrayList中。