public class abc {
public static void main(String args[]) {
Hero hero1=new Hero(1,"a","A");
Hero hero2=new Hero(2,"b","B");
Hero hero3=new Hero(3,"v","v");
Lined l=new Lined();
l.add(hero1);
l.add(hero3);
l.add(hero2);
l.show();
System.out.println(l.getLength(l.getHead()));
}
}
class Lined{
Hero head=new Hero(0,"","");
public void add(Hero hero) {
Hero temp=head;
while(true) {
if(temp.next==null) {
break;
}
temp=temp.next;
}
temp.next=hero;
}
public void show() {
Hero temp=head;
if(head.next==null) {
System.out.println("空");
}
while(true) {
if(temp.next==null) {
break;
}
temp=temp.next;
System.out.println(temp);
}
}
public int getLength(Hero head) { //得链表节点个数
if(head.next==null) {
return 0;
}
int length=0;
Hero cur=head.next;
while(cur!=null) {
length++;
cur=cur.next;
}
return length;
}
public Hero getHead() { //给getLength传head
return head;
}
}
class Hero { //设置对象
public int no;
public String name;
public String nickname;
public Hero next;
public Hero(int no, String name, String nickname) {
this.no = no;
this.name = name;
this.nickname = nickname;
}
public String toString() {
return "HeroNode [no=" + no + ", name=" + name + ", nickname=" + nickname + "]";
}
}
结果
HeroNode [no=1, name=a, nickname=A]
HeroNode [no=3, name=v, nickname=v]
HeroNode [no=2, name=b, nickname=B]
3