双指针: c++: class Solution { public: ListNode* deleteNode(ListNode* head, int val) { ListNode* low = head; ListNode* p = head; if(head->val == val){ return head->next; } head = head->next; while(head != nullptr){ if(head->val == val){ low->next = head->next; return p; } head = head->next; low = low->next; } return p; } }; class Solution { public: ListNode* deleteNode(ListNode* head, int val) { if(head->val == val){ return head->next; } ListNode* low = head; ListNode* fast = head->next; while(fast != nullptr && fast->val !=val){ low = low->next; fast = fast->next; } // 跳出循环说明fast.val == val if(fast != nullptr){ low->next = fast->next; } return head; } }; python class Solution: def deleteNode(self, head: ListNode, val: int) -> ListNode: if head.val == val: return head.next pre = head cur = head.next while cur and cur.val != val: cur = cur.next pre = pre.next pre.next = cur.next return head