在讲如何删除所有关键字为key的节点之前,我们先讲一下如何删除第一次出现关键字为key的节点
删除第一次出现关键字为key的节点
public ListNode searchPrev(int key) {
ListNode cur = this.head;
while(cur.next != null) {
if(cur.next.data == key) {
return cur;
}
cur = cur.next;
}
return cur;
}
public void remove(int key) {
if(this.head.data == key) {
this.head = this.head.next;
return;
}else {
//找到要删除节点的前驱
ListNode prev = searchPrev(key);
if(prev == null) {
System.out.println("该数字不存在!");
return;
}else {
ListNode del = prev.next;
prev.next = del.next;
}
}
}
分析:
1、判断头节点是否为要删除的节点
2、如果头节点不是,则找到要删除节点的前一个节点
删除所有关键字为key的节点
public void removeAllKey(int key) {
ListNode prev = this.head;
ListNode cur = this.head.next;
while(cur != null) {
if(prev.next.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;
}
}