java 简单的链表和二叉树添加元素

不用库函数的方法,用自己定义的方法将链表添加元素并依次输出。

class ListNode
{
	int date;
	ListNode next=null;
}

package ssss;

public class List 
{

	public static void main(String[] args)
	{
		   ListNode  a =  new ListNode(5);
           a.add(new ListNode(10));
           a.add(new ListNode(20));
           a.add(new ListNode(30));
           a.dy();
	}
}
class ListNode
{
	int date;
	ListNode next=null;
	public ListNode(int date)
	{
		    this.date=date;
	}
    public void add(ListNode the)
    {
    	    if(next==null)     //next没有元素,则直接添加。
    	        next=the;
    	    else  next.add(the); //next不为空,则递归下一个next。
    }
     public void dy()
     {
    	
    	System.out.println(date);
    	if(next!=null) 
    	 next.dy();
    	
    	  
     }
}


二叉树根据小的放入左子树,大的放入右子树,可以用前中后序依次打出。

package ssss;
public class tree {
	public static void main(String[] args) {
            treee a =new treee(5);
              a.add(new treee(3));
              a.add(new treee(20));
              a.add(new treee(1));
              a.add(new treee(15));
              a.dy();
	}

}
class treee
{
		treee l;
		treee r;
		int date;
		public treee(int date)
		{
			   this.date=date;
		}
		public void add(treee the)
		{
			if(the.date<date)        //判断下一个树与根节点大小,小放左子树
			{
				if(l==null)    //左子树为空则直接添加到左子树。
				   l=the;
				else l.add(the);//不为空则以这个为根节点开始递归下一个为空的结点。
			}
			else
			{
				if(r==null)
					r=the;
				else r.add(the);
			}
		}
		public void dy()
		{
			System.out.println(date);
		     if(l!=null)	   l.dy();
			if(r!=null)    r.dy();
		}
		
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值