1.题目

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

示例1:

203. 移除链表元素 - 图1

  1. 输入:head = [1,2,6,3,4,5,6], val = 6
  2. 输出:[1,2,3,4,5]
  3. 输入:head = [], val = 1
  4. 输出:[]
  5. 输入:head = [7,7,7,7], val = 7
  6. 输出:[]

提示:

  • 列表中的节点在范围 [0, 104]
  • 1 <= Node.val <= 50
  • 0 <= k <= 50

2.思路

这种题目类似于找链表中某一值,我们尝试用递归来实现

    public ListNode removeElements1(ListNode head, int val) {
        if(head == null){
            return null;
        }
        head.next = removeElements1(head.next,val);
        if (head.val == val){
            return head.next;
        }else {
            return head;
        }
    }

官方给出了一种哨兵模式的解法:

  public ListNode removeElements2(ListNode head, int val) {
    ListNode sentinel = new ListNode(0);
    sentinel.next = head;

    ListNode prev = sentinel, curr = head;
    while (curr != null) {
      if (curr.val == val) prev.next = curr.next;
      else prev = curr;
      curr = curr.next;
    }
    return sentinel.next;
  }