java 中链表的定义与使用方法
java中链表的定义与使用方法
Java实现链表主要依靠引用传递,引用可以理解为地址,链表的遍历多使用递归,这里我存在一个疑问同一个类的不同对象的的相同方法的方法内调用算不算递归.
这里我写的是单向链表;
实例代码:
packagecom.example.java;
publicclassMyLink{
publicstaticvoidmain(String[]args){
Linkl=newLink();
mytype[]la;
mytypedsome=newmytype("韩敏","dsome",21);
mytypeshao=newmytype("邵晓","john",45);
mytypehua=newmytype("华晓风","jam",46);
mytypeduo=newmytype("余小风","duo",1000);
mytypewang=newmytype("王秋","jack",21);
mytypeshi=newmytype("韩寒","bob",3000);
mytypeyu=newmytype("于冬","keven",30);
l.add(dsome);//测试增加节点
l.add(shao);
l.add(hua);
l.add(wang);
l.add(shi);
l.add(duo);
l.add(yu);
System.out.println("链表长度:"+l.length());//链表长度
la=l.toArray();
for(inti=0;i=this.count||index<0){
System.out.print("越界错误");//测试用
returnnull;
}else{
this.foot=0;
returnthis.root.getNode(index);
}
}
publicbooleancontains(mytypedata){//判断链表数据是否含data
if(data==null)
returnfalse;
returnthis.root.iscontain(data);
}
publicvoidremove(mytypedata){//删除指定数据节点
if(this.contains(data)){
if(this.root.data.equals(data)){
this.root=this.root.next;
this.count--;
}
else{
this.count--;
this.root.next.removeNode(root,data);
}
}else{
System.out.print("删除错误");//测试用
}
}
publicmytype[]toArray(){//把链表转化成对象数组
if(this.count==0){
returnnull;
}
this.foot=0;
this.Larray=newmytype[this.count];
this.root.toArrayNode();
returnthis.Larray;
}
}
packagecom.example.java;
publicclassmytype{
privateStringname;
privateStringpeople;
privateintage;
publicmytype(Stringname,Stringpeople,intage){//链表中的数据(可自定义)
this.name=name;
this.people=people;
this.age=age;
}
publicbooleanequals(mytypedata){//判断数据是否相同
if(this==data){
returntrue;
}
if(data==null){
returnfalse;
}
if(this.name.equals(data.name)&&this.people.equals(data.people)&&this.age==data.age){
returntrue;
}else{
returnfalse;
}
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetPeople(){
returnpeople;
}
publicvoidsetPeople(Stringpeople){
this.people=people;
}
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}
publicStringgetInfo(){
return"名字:"+this.name+"\n"+
"人物:"+this.people+"\n"+
"年龄:"+this.age;
}
}
测试效果如下:
链表长度:7 名字:韩敏 人物:dsome 年龄:21 名字:邵晓 人物:john 年龄:45 名字:华晓风 人物:jam 年龄:46 名字:王秋 人物:jack 年龄:21 名字:韩寒 人物:bob 年龄:3000 名字:余小风 人物:duo 年龄:1000 名字:于冬 人物:keven 年龄:30 是否包含多余:true 删除多余后 名字:韩敏 人物:dsome 年龄:21 名字:邵晓 人物:john 年龄:45 名字:华晓风 人物:jam 年龄:46 名字:王秋 人物:jack 年龄:21 名字:韩寒 人物:bob 年龄:3000 名字:于冬 人物:keven 年龄:30 利用索引方法输出全部数据 名字:韩敏 人物:dsome 年龄:21 名字:邵晓 人物:john 年龄:45 名字:华晓风 人物:jam 年龄:46 名字:王秋 人物:jack 年龄:21 名字:韩寒 人物:bob 年龄:3000 名字:于冬 人物:keven 年龄:30 是否包含多余:false 执行清空操作后链表长度:0是否为空链表:true
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!