思路分析:
- 有效节点个数即单链表的长度
- 在遍历的时候定义一个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.shanchu(1);
lianbiao.changdu(lianbiao.getHead());
lianbiao.list();
}
}
//定义一个SingleLinkedList 管理我们的英雄
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){ //注意一下 都用temop.next.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;
}
}
}
//定义一个heroNode,每一个heroNode对象就是一个节点
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 + '\'' +
'}';
}
}
代码运行效果如下: