代码实现一(双指针):
public class Solution {
public ListNode deleteNode(ListNode head, int val) {
//判断链表是否为空
if (head == null) {
return null;
}
//由于下边使用快指针判断值所以会漏掉头节点,所以单独判断
if (head.val == val) {
return head.next;
}
//定义快慢指针
ListNode one = head.next;
ListNode two = head;
//循环
while (one != null) {
//当值相等时就让慢指针的next指向快指针的next
if (one.val == val) {
one = one.next;
two.next = one;
} else {
one = one.next;
two = two.next;
}
}
//输出头节点
return head;
}
}
代码实现二(头节点辅助):
public class Solution {
public ListNode deleteNode (ListNode head, int val) {
//创建头节点
ListNode first = new ListNode(Integer.MIN_VALUE);
first.next = head;
ListNode one = first;
//循环要从头节点的next开始
while(one.next != null){
//相等,则把想等的替换掉
if(one.next.val == val){
one.next = one.next.next;
}
one = one.next;
}
return first.next;
}
}