给定链表头节点,删除链表中所有含指定值的的节点。
class Node {
public Node next;
public int value;
public Node(int data) {
value = data;
}
}
public static Node removeNode(Node head, int value) {
//先从头部节点开始找,找到值不为value的节点,跳出循环
while (head != null) {
if (head.value != value) {
break;
}
head = head.next;
}
//当前节点
Node cur = head;
//当前节点的前一个节点,前一部分已经去掉了头部节点value值相等的情况。
Node pre = null;
//判断当前是否为null
while(cur != null){
//判断当前节点是否符合要求
if(cur.value == value){
//让当前节点的前一个节点的next指向当前节点的next节点,即跳过当前节点
pre.next = cur.next;
}else{
//设置当前节点为下一次循环时的前一个节点
pre = cur;
}
//设置下次循环时,当前节点为当前节点的下一个节点。
cur = cur.next;
}
return head;
}