此单链表有头结点

定义一个结点类,存储信息

public class Node {
int no;//编号
String name;//姓名
String nickName;//别名
Node next;
//初始化结点信息
public Node(int no,String name,String nickName) {
this.no = no;
this.name = name;
this.nickName = nickName;
}
@Override
public String toString() {
return "Node{" +"no=" + no +
", name='" + name + '\'' +
", nickName='" + nickName + '\'' +
'}';
}
}

PS:下面简单实现对单链表的增删改查

单链表(java)——简单实现_头结点

头结点不能动,所以在方法中会定义一个辅助变量(指针)

Node temp = head;

添加结点原理

if(node.no<temp.next.no){//编号与后面一个元素作比较,小于则插入在它之前
//插入关键
node.next = temp.next;
temp.next = node;
break;
}

定义一个单链表接口

public interface MyLinkList {
void addNode(Node node);//在末尾添加结点
void show();//展示单链表
void addNodeById(Node node);按顺序添加结点信息
void updateNode(Node node);//更新结点
void deleteNode(int no);//删除结点
}

实现单链表

public class MyLinkListImpl implements MyLinkList {

//初始化头结点
private final Node head =new Node(0,"","");

//在单链表结尾添加结点
public void addNode(Node node){
Node temp = head;
//遍历单链表
while(true){
if(temp.next==null){
break;
}
temp = temp.next;
}
temp.next = node;
}
//展示单链表
public void show(){
Node temp = head;
if(temp.next==null){
System.out.println("链表为空");
return;
}
while(true){
if(temp.next==null){
break;
}
System.out.println(temp.next);
temp = temp.next;
}
}
//按顺序添加结点
public void addNodeById(Node node){
Node temp = head;
boolean flag = false;
while(true){
if(temp.next==null){
break;
}
if(node.no<temp.next.no){
break;
}else if(node.no==temp.next.no){
flag = true;
}
temp = temp.next;
}
if(flag){
System.out.println("当前位置已有人"+node.no);
}else{
node.next = temp.next;
temp.next = node;
}
}
//更新结点
public void updateNode(Node node){
Node temp = head;
if(temp.next==null){
System.out.println("链表为空----");
return;
}
while(true){
if(temp.next==null){
System.out.println("找不到你要修改的结点");
break;
}else if(temp.next.no== node.no){
temp.next.name = node.name;
temp.next.nickName = node.nickName;
break;
}else if(node.no<0){
System.out.println("请按要求输入");
break;
}
temp = temp.next;
}
}
//删除结点
public void deleteNode(int index){
Node temp = head;
while (true){
if(temp.next==null){
System.out.println("找不到该元素");
break;
}
if(temp.next.no==index){
temp.next = temp.next.next;
break;
}
temp = temp.next;
}
}
}

测试单链表的功能

public class testMyLink {
public static void main(String[] args) {

MyLinkListImpl impl = new MyLinkListImpl();

/*测试在末尾添加结点
impl.addNode(new Node(1,"宋江","及时雨"));
impl.addNode(new Node(4,"李逵","黑旋风"));
impl.addNode(new Node(3,"吴用","智多星"));
impl.addNode(new Node(2,"卢俊义","玉麒麟"));*/

//按编号顺序添加结点
impl.addNodeById(new Node(1,"宋江","及时雨"));
impl.addNodeById(new Node(4,"李逵","黑旋风"));
impl.addNodeById(new Node(3,"吴用","智多星"));
impl.addNodeById(new Node(2,"卢俊义","玉麒麟"));
System.out.println("————修改前—————");
impl.show();

//修改结点
Node newNode = new Node(2,"林冲","豹子头");
impl.updateNode(newNode);
System.out.println("————修改后————");
impl.show();
System.out.println("——————删除后——————");
impl.deleteNode(2);
impl.show();
}
}