1 .首先创建单链表里面包括:
1.头节点 head 并且置空
2.定义一个内部类,private私有化(封装性),定义所要保存的值,和指向下一结点的next指针
public class SinglyLinkedList {//单向链表
private Node head = null;
//结点类
private static class Node{
int value; // 值
Node next; // 下一个结点指针
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
2.定义类方法
public void remove(int value){
Node pre = head;//如果head为空就是链表不存在
if (head == null){
throw new RuntimeException("单链表为空");
}
Node point = pre.next;//头指针的下一个对象指针
while(pre != null){
if (pre.value == value){//head指针指向的第一个元素就是要删除的元素
pre= point;
pre.next = point.next;
head = pre;
return;
}else if (point.value == value){//不是第一个元素的时候
pre.next = point.next;
return;
}else {//如果当前结点不是所要删除的值,就将指针往下移
pre = pre.next;
point = point.next;
}
}
}
1.定义pre指针指向head,如果head为null,链表就不存在
2.如果链表存在,就定义一个衔接指针point指向头节点的下一个结点(也有可能为空)
3.根据情况划分,删除结点
3.试例
@Test
public void show(){
SinglyLinkedList singlyLinkedList = new SinglyLinkedList();
singlyLinkedList.addNode(1);
singlyLinkedList.addNode(2);
singlyLinkedList.addNode(3);
singlyLinkedList.addNode(4);
singlyLinkedList.addNode(5);
singlyLinkedList.remove(5);
singlyLinkedList.loop1((value)->{
System.out.println(value);
}
);
}
@Test
public void show(){
SinglyLinkedList singlyLinkedList = new SinglyLinkedList();
singlyLinkedList.addNode(1);
singlyLinkedList.addNode(2);
singlyLinkedList.addNode(3);
singlyLinkedList.addNode(4);
singlyLinkedList.addNode(5);
singlyLinkedList.remove(1);
singlyLinkedList.loop1((value)->{
System.out.println(value);
}
);
}
声明:纯纯新手大佬勿cue,有错误及时反馈。