删除单链表中值为key的第一个节点
public void removeKey(int key) {
if (this.head == null) {
System.out.println("链表为空");
return;
}
if (this.head.data == key) {
this.head = this.head.next;
return;
}
Node index = findKeyIndex(key);
if (index == null) {
System.out.println("该节点的前驱不存在");
return;
}
index.next = index.next.next;
}
public Node findKeyIndex(int key) {
if (this.head == null) {
System.out.println("链表为空");
return null;
}
Node cur = this.head;
while (cur.next != null) {
if (cur.next.data == key) {
return cur;
}
cur = cur.next;
}
return null;
}
删除单链表中值为key的所有节点
public void removeAllKey(int key) {
if (this.head == null) {
return;
}
Node prev = this.head;
Node cur = this.head.next;
while (cur != null) {
if (cur.data == key) {
prev.next = cur.next;
cur = cur.next;
} else {
prev = cur;
cur = cur.next;
}
}
if (this.head.data == key) {
this.head = this.head.next;
}
}
清空链表
public void clean() {
this.head = null;
}
单链表其他操作,增删查改完整代码