题目描述

image.png

解题思路

由于头节点也需要判断,所以采用虚拟头节点的方法,具体参照专题的虚拟头节点章节。

  1. class Solution {
  2. public ListNode deleteNode(ListNode head, int val) {
  3. if (head == null) {
  4. return null;
  5. }
  6. ListNode dummy = new ListNode(-1);
  7. ListNode pre = dummy;
  8. pre.next = head;
  9. ListNode cur = pre.next;
  10. while (cur != null) {
  11. if (cur.val == val) {
  12. pre.next = cur.next;
  13. }else {
  14. pre = pre.next;
  15. }
  16. cur = cur.next;
  17. }
  18. return dummy.next; // 返回虚拟头节点
  19. }
  20. }