力扣,https://leetcode.cn/problems/shan-chu-lian-biao-de-jie-dian-lcof/description/
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteNode(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
pre, cur = ListNode(-1), head
pre.next = cur
while cur:
if cur.val == val:
pre.next = cur.next
if cur == head:
return pre.next
break
pre = cur
cur = cur.next
return head
Java
// 自己写的答案
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if (head == null) {
return null;
}
if (head.val == val) {
return head.next;
}
ListNode pre = head, cur = head.next;
while (cur != null) {
if (cur.val != val) {
pre = cur;
cur = cur.next;
} else {
pre.next = cur.next;
break;
}
}
return head;
}
}