结构体
package com.singleLikedlist;
class hero {
public int num;
public String name;
public hero next;
public hero(int num, String name) {
this.num = num;
this.name = name;
}
@Override
public String toString() {
return "com.singleLikedlist.hero{" +
"num=" + num +
", name='" + name + '\'' +
'}';
}
}
链表函数
package com.singleLikedlist;
public class singleLikedlist {
private hero headnode=new hero(001,"");
public void add(hero node)
{
hero temp=headnode;
while(true)
{
if(temp.next==null)
{
break;
}
temp=temp.next;
}
temp.next=node;
}
public void show()
{
hero temp=headnode.next;
if(temp==null)
{
System.out.println("链表为空");
return;
}
while(true)
{
if(temp==null)
{
System.out.println("链表遍历完");
break;
}
System.out.println(temp);
temp=temp.next;
}
}
public void byorder(hero node)
{
boolean flag=false;
hero temp=headnode;
while(true)
{
if(temp.next==null)
{
break;
} else if (temp.next.num>node.num) {
break;
}
else if(temp.next.num== node.num)
{
flag=true;
}
temp=temp.next;
}
if(flag)
{
System.out.println("重复");
}
else
{
node.next=temp.next;
temp.next=node;
}
}
public void update(hero updatenode)
{
boolean flag=false;
hero tmep=headnode.next;
if(headnode.next==null)
{
System.out.println("链表为空");
return;
}
while(true)
{
if(tmep.next==null)
{
break;
}
else if(tmep.num== updatenode.num)
{
flag=true;
break;
}
tmep=tmep.next;
}
if(flag)
{
tmep.name= updatenode.name;
}
else
{
System.out.println("没有找到");
}
}
public void delete(int num)
{
boolean flag=false;
hero temp=headnode;
while(true)
{
if(temp.next==null)
{
System.out.println("没有找到");
break;
}
else if (temp.next.num==num) {
flag=true;
break;
}
temp=temp.next;
}
if(flag)
{
temp.next=temp.next.next;
}
else
{
System.out.println("没有找到节点");
}
}
}
测试
package com.singleLikedlist;
public class text {
public static void main(String[] args) {
hero hero1 = new hero(001,"宋江");
hero hero2 = new hero(002,"李逵");
hero hero3 = new hero(003,"张飞");
hero hero4 = new hero(004,"赵云");
hero hero5 = new hero(001,"宋明");
singleLikedlist singleLikedlist = new singleLikedlist();
singleLikedlist.byorder(hero1);
singleLikedlist.byorder(hero4);
singleLikedlist.byorder(hero3);
singleLikedlist.byorder(hero2);
singleLikedlist.show();
System.out.println("---------------");
singleLikedlist.delete(1);
singleLikedlist.show();
// System.out.println("改后");
// singleLikedlist.update(hero5);
//singleLikedlist.show();
}
}