之前写过C语言的文章,Java思想不变只是换种写法,因此不做过多解释说明,代码里已经很清晰
public class LinkListDemo {
public static void main(String[] args) {
LinkList lst=new LinkList();
lst.add(1,"Error");
lst.add(2,"Starry");
lst.insert(3,3,"lian");
lst.findId(1);
lst.revise(1,"haha");
lst.delId(3);
lst.show();
}
}
class LinkNode{
int id;
String name;
LinkNode next;
public LinkNode(int id,String name){
this.id=id;
this.name=name;
}
public void sayHello(){
System.out.println("my name is "+name+",and my id is "+id+".");
}
}
class LinkList{
LinkNode head=new LinkNode(0,"");
public void add(int id,String name){
LinkNode node=new LinkNode(id,name);
LinkNode temp=head;
while (temp.next!=null){
temp=temp.next;
}
temp.next=node;
}
public void show(){
LinkNode temp=head;
while (temp.next!=null){
temp=temp.next;
temp.sayHello();
}
}
public void findId(int id){
LinkNode temp=head;
while (temp.next!=null){
temp=temp.next;
if(temp.id==id){
temp.sayHello();
return;
}
}
System.out.println("没有此id哦~");
}
public void delId(int id){
LinkNode temp=head;
while (temp.next!=null){
LinkNode cur=temp;
temp=temp.next;
if(temp.id==id){
cur.next=temp.next;
System.out.println("删除"+temp.name);
return;
}
}
System.out.println("没有此id哦~");
}
public int length(){
LinkNode temp=head;
int count=0;
while (temp.next!=null){
temp=temp.next;
count++;
}
return count;
}
public void insert(int location,int id,String name){
int len=length();
if(location<1||location>len+1){
System.out.println("插入的位置有误,当前链表长度为"+len);
return;
}
LinkNode temp=head;
LinkNode node=new LinkNode(id,name);
LinkNode cur=head;
while (location!=0){
cur=temp;
temp=temp.next;
location--;
}
cur.next=node;
node.next=temp;
}
public void revise(int id,String newname){
LinkNode temp=head;
while (temp.next!=null){
temp=temp.next;
if(temp.id==id){
temp.name=newname;
return;
}
}
System.out.println("没有此id哦~");
}
}