栈,队列,二叉树常见编码题

(1)栈,计算表达式值,相消值如01相消,以及括号匹配问题

    package 栈与队列用处01匹配消除和括号匹配和计算表达式;
    import java.util.Scanner;
    import java.util.Stack;
    public class JiSuan栈计算表达式 {
    	public static void main(String[] args) {
    	Scanner cin=new Scanner(System.in);
        while(cin.hasNext())
        {
        	String sstr=cin.nextLine();
        	if(sstr.compareTo("0")==0) break;
        	String []str=sstr.split(" ");
        	Stack<Double> s=new Stack<Double>();
        	double m=Double.parseDouble(str[0]);
        	s.push(m);
        	for(int i=1;i<str.length;i++)
        	{
        		if(i%2==1)
        		{
        			if(str[i].compareTo("+")==0)
        			{
        				double help=Double.parseDouble(str[i+1]);
        				s.push(help);
        			}
        			if(str[i].compareTo("-")==0)
        			{
        				double help=Double.parseDouble(str[i+1]);
        				s.push(-help);
        			}
        			if(str[i].compareTo("*")==0)
        			{
        				double help=Double.parseDouble(str[i+1]);
        				double ans=s.peek();
        				s.pop();
        				ans=ans*help;
        				s.push(ans);
        			}
        			if(str[i].compareTo("/")==0)
        			{
        				double help=Double.parseDouble(str[i+1]);
        				double ans=s.peek();
        				s.pop();
        				ans=ans/help;
        				
        				s.push(ans);
        			}
        		}
        	}
        	double ans=0;
        	while(!s.isEmpty())
        	{
        		ans=ans+s.peek();
    		s.pop();
    		
    	}
    	System.out.println(String.format("%.2f", ans));
    }
	}
    }

2.括号匹配

    package Huawei;
    import java.util.Scanner;
    import java.util.Stack;
    public class Main182
    {
      public static void main(String[] args)
      {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext())
       {
          /** 利用栈先进后出(FILO)特性*/
          Stack<Character> stack = new Stack<>();
          String str = sc.nextLine();
          char[] cs = str.toCharArray();
          for (int i = 0; i < cs.length; i++)
          {
             if (cs[i] == '(' || cs[i] == '{' || cs[i] == '[')
             {
               stack.push(cs[i]);
             }
             else
             {
               if (cs[i] == ')')
               {
                 if (stack.peek() == '(')
                 {
                   stack.pop();
                 }
               }
               if (cs[i] == '}')
               {
                 if (stack.peek() == '{')
                 {
                   stack.pop();
                 }
               }
               if (cs[i] == ']')
               {
                 if (stack.peek() == '[')
                 {
                   stack.pop();
                 }
               }
             }
          }
          if(stack.isEmpty()){
    
             System.out.println("true");
          }
          else{
    
             System.out.println("false");
          }
        }
      }
    }

(2.队列问题)

    package 栈与队列用处01匹配消除和括号匹配和计算表达式;
    import java.util.ArrayDeque;
    import java.util.Scanner;
    public class Mainqueue {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner cin=new Scanner(System.in);
    while(cin.hasNext())
    {
    	int n=cin.nextInt();
    	int k=cin.nextInt();
    	int num=1;
    	ArrayDeque queue=new ArrayDeque();
    	for(int i=0;i<n;i++)
    	{
    		queue.offer(i+1);
    	}
    	while(queue.size()>1)
    	{
    		int top=(int)queue.poll();
    		if(num%k!=0&&num%10!=k)
    		{
    			queue.offer(top);
    		}
    		num++;
    	}
    	System.out.println(queue.peek());
    }
	}

    }

(3)二叉树计算表达式

    package 栈与队列用处01匹配消除和括号匹配和计算表达式;
    
    import java.util.ArrayList;
    import java.util.Stack;
    public class Treecal {
    	public static String str="";
    	class Node6 {
    		Node6 left;
    		Node6 right;
    		String data;
    		
    		public Node6(){}
    		public Node6(String data){
    			this.data=data;
    		}
    		//前序遍历
    		public void frontbianli(Node6 n){
    			System.out.print(n.data+" ");//输出结点n的数据
    			if(n.left!=null)
    			n.frontbianli(n.left);
    			if(n.right!=null)
    			n.frontbianli(n.right);	
    		}
    		//中序遍历
    		public void middlebianli(Node6 n){
    			if(n.left!=null){
    				n.middlebianli(n.left);
    			}
    			System.out.print(n.data+" ");//输出结点n的数据
    			if(n.right!=null){
    				n.middlebianli(n.right);
    			}	
    		}
    		//后序遍历
    		public String behindbianli(Node6 n){
    			if(n.left!=null){
    				n.behindbianli(n.right);
    			}
    			if(n.right!=null){
    				n.behindbianli(n.left);
    			}	
    			str = str+n.data;//输出结点n的数据
    			return str;
    		}
    		}
    
    Node6 root=null;//初始化根结点
    public String creattree(){
    	ArrayList<Node6>number =new ArrayList<Node6>();//创建一个结点类型数组队列,用来存放数字
    	ArrayList<Node6>symbol =new ArrayList<Node6>();//创建一个结点类型数组队列,用来存放符号
    	number.add(new Node6("1"));//添加元素
    	number.add(new Node6("2"));
    	number.add(new Node6("6"));
    	number.add(new Node6("8"));
    	symbol.add(new Node6("+"));
    	symbol.add(new Node6("+"));
    	symbol.add(new Node6("-"));
    	while(symbol.size()>0){//当存储符号的数组队列大于零时,循环继续,注意:符号数要比数字数少一
    		Node6 num1=number.remove(0);//将存放数字的数组队列的第一个数字移除并把它赋值给num1
    		Node6 num2=number.remove(0);//然后再将存放数字的数组队列的第一个数字移除并把它赋值给num2
    		Node6 s=symbol.remove(0);//将存放符号的数组队列的第一个符号移除并把它赋值给s
    		s.left=num1;//将结点对象num1赋值给s的左结点
    		s.right=num2;//将结点对象num2赋值给s的左结点
    		number.add(0,s);//将符号结点s加入存放数字结点的第一位
    	}
    	root=number.get(0);//将最后一个结点赋值给根节点
    	Node6 n=new Node6();//创建一个新的节点对象
    	/*System.out.println();
    	n.frontbianli(root);//调用前序遍历的方法
    	System.out.println();*/
    	n.middlebianli(root);//调用中序遍历的方法
    	System.out.println();
    	
    	str=n.behindbianli(root);//调用后序遍历的方法
    	return str;
    }
    
    public static int truecal(String str)
    {
    	Stack<Integer> mystack=new Stack<Integer>();
    	int size=str.length();
    	char c[]=str.toCharArray();
    	String ss[]=new String[c.length];
    	for(int i=0;i<c.length;i++)
    	{
    		ss[i]=String.valueOf(c[i]);
    	}
    	int num1,num2,num3 = 0;
    	for(int i=0;i<size;i++)
    	{
    		if(c[i]>='0'&&c[i]<='9')
    		{
    			mystack.push(c[i]-'0');
    		}else{
    			num2=mystack.peek();
    			mystack.pop();
    			num1=mystack.peek();
    			mystack.pop();
    			if(c[i]=='+')
    			{
    				num3=num2+num1;
    			}else
    			if(c[i]=='-')
    			{
    				num3=num2-num1;
    			}else
    			if(c[i]=='*')
    			{
    				num3=num2*num1;
    			}else
    			if(c[i]=='/')
    			{
    				num3=num2/num1;
    			}
    			mystack.push(num3);
    		}
    	}
    	return mystack.peek();
    	
    }
    public static void main(String []args){
    	Treecal two=new Treecal();//创建类的对象
    	String str=two.creattree();//执行创建二叉树的方法
    	System.out.println(str);
    	int ans=truecal(str);
    	System.out.println(ans);
    }
    }

(4)数组二叉树

    
    package 二叉树结构;
    
    public class Arrayto二叉树 {
    
    	public static void main(String[] args) {
    		Erchashu er=new Erchashu();
    		er.setchild(0, 5, true);
    		er.setchild(0, 2, false);
    		System.out.println(er.getdeep());
    		System.out.println(er.getlen());
    		System.out.println(er.getroot());
    		System.out.println(er.getTree(0));
    		System.out.println("-------------------");
    		System.out.print(er.getleft(0)+" ");
    		System.out.print(er.getright(0)+" ");
    		System.out.print("0");
    	}
    }
    class Erchashu{
    	private int deep;
    	private int len;
    	
    	int root;
    	int array[];
    	
    	public Erchashu()
    	{
    		deep=10;
    		len=(int)(Math.pow(2, deep)-1);
    		
    		array=new int[len];
    		array[0]=1;
    		
    		root=array[0];
    	}
    	public Erchashu(int deep,int root)
    	{
    		this.deep=deep;
    		len=(int)(Math.pow(2, deep)-1);
    		this.root=root;
    		array=new int[len];
    		array[0]=root;
    	}
    	
    	public void setchild(int index,int value,boolean isleft)
    	{
    		if(array[index]==0)
    		{
    			System.out.println("节点不合法!");
    		}else if(isleft&&2*index+1<=len+1){
    			
    			array[2*index+1]=value;
    			int i=2*index+1;
    			
    		}else if(2*index+2<=len+2&&!isleft){
    			array[2*index+2]=value;
    			int i=2*index+2;
    		}else{
    			System.out.println("你的数组下标不在范围内!");
    		}
    	}
    	
    	public int getTree(int index)
    	{
    		int ans=array[index];
    		return ans;
    	}
    	
    	public int getleft(int index)
    	{
    		if(index<0||(int)Math.pow(2, deep-1)>len-1)
    		{
    			System.out.println("数组越界或者为root节点!");
    		    return -1;
    		}else{
    			return array[2*index+1];
    		}
    	}
    	public int getright(int index)
    	{
    		if(index<0||(int)Math.pow(2, deep-1)>len-1)
    		{
    			System.out.println("数组越界或者为root节点!");
    		    return -1;
    		}else{
    			return array[2*index+2];
    		}
    	}
    	public int getdeep()
    	{
    		return deep;
    	}
    	public int getlen(){
    		return len;
    	}
    	public int getroot()
    	{
    		return root;
    	}
    }

(5)指针二叉树

    package 二叉树结构;
    
    import java.util.LinkedList;
    import java.util.List;
    
    public class BinaryTree指针 {
    	private static List<Tree> nodelist=null;
    	public static void main(String[] args) {
    	int array[]={4,5,3,2,6,8,9,7,1};
    	//BinaryTree bt=new BinaryTree();
    	CreateTree(array);
    	System.out.println("前序遍历为:");
    	System.out.println("------");
    	Tree tree=nodelist.get(0);
    	pretrack(tree);
    	System.out.println();
    	System.out.println("中序遍历为:");
    	System.out.println("------");
    	intrack(tree);
    	System.out.println();
    	
    	
    	System.out.println("后序遍历为:");
    	System.out.println("-------");
    	
    	
    	
    	aftertrack(tree);
    	
    	
    	}
    
    
    
    public static class Tree{
    	int data;
    	Tree left;
    	Tree right;
    	public Tree(int data)
    	{
    		left=null;
    		right=null;
    		this.data=data;
    	}
    }
    	public  static void CreateTree(int array[])
    	{
    		nodelist=new LinkedList<Tree>();
    		
    		for(int i=0;i<array.length;i++)
    		{
    			nodelist.add(new Tree(array[i]));
    				
    		}
    		for(int i=0;i<array.length/2-1;i++)
    		{
    			nodelist.get(i).left=nodelist.get(i*2+1);
    			
    			nodelist.get(i).right=nodelist.get(i*2+2);
    		}
    		int i=array.length/2-1;
    		if(array.length%2==1)
    		{
    			nodelist.get(i).left=nodelist.get(i*2+1);
    			
    			nodelist.get(i).right=nodelist.get(i*2+2);
    		}else{
    			nodelist.get(i).left=nodelist.get(i*2+1);
    		}
    		
    	}
    	
    	public static void pretrack(Tree tree)
    	{
    		if(tree==null)
    		{
    			return;
    		}
    		
    		System.out.print(tree.data+" ");
    		pretrack(tree.left);
    		
    		pretrack(tree.right);
    	}
    	
    	public static void intrack(Tree tree)
    	
    	{
    		if(tree==null)
    		{
    			return;
    		}
    		
    		intrack(tree.left);
    		
    		System.out.print(tree.data+" ");
    		
    		intrack(tree.right);
    	}
    	
    	
    	public static void aftertrack(Tree tree)
    	{
    		if(tree==null)
    		{
    			return;
    		}
    		
    		aftertrack(tree.left);
    		
    		aftertrack(tree.right);
    		
    		System.out.print(tree.data+" ");
    	}
        }

(6)知前中求后序遍历


    package 二叉树结构;
    import java.util.Scanner; 
    public class Main二叉树知前中求后 {
    	     static String str; 
    	     public static void main(String[] args) { 
    	         Scanner sc = new Scanner(System.in); 
    	         /*String[] strpre;//这里要用数组接受输入 
    	         String[] strin; 
    	         int n; 
    	         while (sc.hasNext()) { 
    	             n = sc.nextInt(); 
    	             strpre = new String[n]; 
    	             strin = new String[n]; 
    	             str = ""; 
    	             for (int i = 0; i < n; i++) 
    	                 strpre[i] = sc.next(); 
    	             for (int i = 0; i < n; i++) 
    	                 strin[i] = sc.next(); */
    	         int strpre[]={4 ,5 ,2 ,7 ,1, 6 ,3, 8, 9 };
    	 		int strin[]={7, 2 ,1, 5 ,6, 4 ,8 ,3 ,9 };
    	 		
    	             Node3 node = buildTree(strpre, strin); 
    	             postOrder(node); 
    	             System.out.println(str.trim()); 
    	         } 
    	     
    	     // 建立二叉树 
    	     public static Node3 buildTree(int[] strpre, int[] strin) { 
    	        if (strpre.length <= 0) 
    	         {
    	        	
    	             return null;
    	         }
    	         // 建立一个根节点 
    	         int s = strpre[0]; 
    	         Node3 root = new Node3(s); 
    	         // 以根节点为中心,将中序分为两个子序列 
    	         int i, index = 0; 
    	         for (i = 0; i < strin.length; i++) { 
    	             if (strin[i]==s) { 
    	                 index = i; 
    	                 break; 
    	             } 
    	         } 
    	         int[] leftin = new int[index];        以根节点划分成成两个子序列,左右子树
    	         int[] rightin = new int[strin.length - index - 1]; 
    	         for (i = 0; i < index; i++) 
    	             leftin[i] = strin[i]; 
    	         int j = index+1; 
    	         for (i = 0; j < strin.length; i++,j++)  
    	             rightin[i] = strin[j]; 
    	         // 根所左中序的长度,将先序分为左右两个子先序  
    	         int leftlen = leftin.length; 
    	         int[] leftpre = new int[leftlen]; 
    	         int[] rightpre = new int[strpre.length - leftlen - 1]; 
    	         for (i = 0; i < leftlen; i++) 
    	             leftpre[i] = strpre[i + 1]; 
    	         for (i = 0; i < strpre.length - leftlen - 1; i++) 
    	             rightpre[i] = strpre[i + leftlen + 1]; 
    	         root.lChild = buildTree(leftpre, leftin); 
    	         root.rChild = buildTree(rightpre, rightin); 
    	         return root; 
    	     } 
    	     // 后序遍历 输出
    	     public static void postOrder(Node3 node) { 
    	         if (node != null) { 
    	             postOrder(node.lChild); 
    	             postOrder(node.rChild); 
    	             str += " " + node.data; 
    	         } 
    	     } 
    }
    	 class Node3 { ///相当于结构体
    	     public int data; 
    	     public Node3 lChild; 
    	     public Node3 rChild; 
    	     public Node3(int data) { 
    	         this.data = data; 
    	         this.lChild = null; 
    	         this.rChild = null; 
    	     } 
    	 } 

(7)最小生成树并查集

    package 二叉树结构;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Scanner;
     
    public class Main最小生成树csp并查集 {
     
    	static int [] par=null;
    	static int [] rank=null;
    	
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner scan=new Scanner(System.in);
    		int n=scan.nextInt();
    		int m=scan.nextInt();
    		Edge [] es=new Edge[m];
    		ArrayList<Edge> alist=new ArrayList<Edge>();
    		for(int i=0;i<m;++i){
    			es[i]=new Edge(scan.nextInt(),scan.nextInt(),scan.nextInt());
    			alist.add(es[i]);
    		}
    		par=new int[n+5];
    		rank=new int[n+5];
    		init(n);
    		Collections.sort(alist);
    		for(int i=0;i<alist.size();++i){
    			unite(alist.get(i).a,alist.get(i).b);
    			if(same(1, n)){
    				System.out.println(alist.get(i).day);
    				return;
    			}
    		}
    	}
    	
    	public static  void init(int n){
    		for(int i=1;i<=n;++i){
    			par[i]=i;
    			rank[i]=0;
    		}
    	}
    	
    	public static int find(int x){
    		if(par[x]==x){
    			return x;
    		}
    		else{
    			return par[x]=find(par[x]);
    		}
    	}
    	
    	public static void unite(int x,int y){
    		x=find(x);
    		y=find(y);
    		if(x==y){
    			return ;
    		}
    		if(rank[x]<rank[y]){
    			par[x]=y;
    		}
    		else{
    			par[y]=x;
    			if(rank[x]==rank[y]){
    				rank[x]++;
    			}
    		}
    	}
    	
    	public static  boolean same(int x,int y){
    		return find(x)==find(y);
    	}
     
    }
     
     
    class Edge implements Comparable<Edge>{
    	
    	int a;
    	int b;
    	int day;
     
    	Edge(int a,int b,int day){
    		this.a=a;
    		this.b=b;
    		this.day=day;
    	}
    	
    	public int compareTo(Edge e){
    		if(this.day<e.day){
    			return -1;
    		}
    		else if(this.day>e.day){
    			return 1;
    		}
    		else{
    			return 0;
    		}
    	}
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tronhon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值