不用库函数的方法,用自己定义的方法将链表添加元素并依次输出。
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();
}
}