思路分析:
有效节点个数即单链表的长度在遍历的时候定义一个length,每遍历一个节点,length++,最后返回sum即可
package com
.ran
;
import java
.util
.Scanner
;
public class hello {
public static void main(String
[] args
) {
HeroNode hero1
=new HeroNode(1,"ran","qwe");
HeroNode hero2
=new HeroNode(2,"rasd","asd");
HeroNode hero3
=new HeroNode(3,"zxc","zxc");
HeroNode hero4
=new HeroNode(4,"asdasd","fgh");
SingleLinkedList lianbiao
=new SingleLinkedList();
lianbiao
.add2(hero1
);
lianbiao
.add2(hero4
);
lianbiao
.add2(hero2
);
lianbiao
.add2(hero3
);
lianbiao
.changdu(lianbiao
.getHead());
lianbiao
.list();
}
}
class SingleLinkedList{
HeroNode head
=new HeroNode(0,"","");
public HeroNode
getHead() {
return head
;
}
public void add(HeroNode heroNode
){
HeroNode temp
=head
;
while (true){
if(temp
.next
==null
){
break;
}
temp
=temp
.next
;
}
temp
.next
=heroNode
;
}
public void add2(HeroNode heroNode
){
HeroNode temp
=head
;
boolean qwe
=false;
while (true){
if (temp
.next
==null
){
break;
}
if(temp
.next
.no
>heroNode
.no
){
break;
}
else if(temp
.next
.no
==heroNode
.no
){
qwe
=true;
break;
}
temp
=temp
.next
;
}
if(qwe
){
System
.out
.println("存在了添加不了");
}else {
heroNode
.next
=temp
.next
;
temp
.next
=heroNode
;
}
}
public static void changdu(HeroNode head
){
HeroNode temp
=head
;
int length
=0;
if(head
==null
){
System
.out
.println("空");
System
.out
.println("chang du wei "+length
);
}
while (true){
if(temp
.next
==null
){
break;
}
length
++;
temp
=temp
.next
;
}
System
.out
.println("chang du wei "+length
);
}
public void list(){
if(head
.next
==null
){
System
.out
.println("kong");
return;
}
HeroNode temp
=head
;
while (true){
if(temp
.next
==null
){
break;
}
System
.out
.println(temp
.next
);
temp
=temp
.next
;
}
}
}
class HeroNode{
public int no
;
public String name
;
public String chuohao
;
public HeroNode next
;
public HeroNode(int no
, String name
, String chuohao
) {
this.no
= no
;
this.name
= name
;
this.chuohao
= chuohao
;
}
@Override
public String
toString() {
return "HeroNode{" +
"no=" + no
+
", name='" + name
+ '\'' +
", chuohao='" + chuohao
+ '\'' +
'}';
}
}
代码运行效果如下:
转载请注明原文地址:https://tech.qufami.com/read-18432.html