思路:
1.双指针prev,cur,当 cur.val == val
时,执行 prev.next = curr.next
删除结点
2.递归函数public ListNode deleteNode(ListNode head, int val)
表示删除链表中值等于val
的结点
终止条件
1.当head
等于空的时候,直接返回head
,因为一个空的链表我们是没法删除的,if (head == null) return head;
2.如果head
结点不等于空,并且head
结点的值等于val
,直接返回head结点的下一个结点head.next = deleteNode(head.next, val); return head;
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head == null) return null;
if(head.val == val) return head.next;
ListNode prev = new ListNode(-1);
prev.next = head;
ListNode curr = head;
while(curr != null){
if(curr.val == val){
prev.next = curr.next;
return head;
}
curr = curr.next;
prev = prev.next;
}
return head;
}
}
public ListNode deleteNode(ListNode head, int val) {
if (head == null)
return head;
if (head.val == val)
return head.next;
head.next = deleteNode(head.next, val);
return head;
}
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head == null) return null;
if(head.val == val) return head.next;
ListNode pre = head;
ListNode cur = head.next;
while(cur.next != null && cur.val != val){
pre = cur;
cur = cur.next;
}
if(cur!= null){
pre.next = cur.next;
}
return head;
}
}