Given the head
of a linked list and an integer val
, remove all the nodes of the linked list that has Node.val == val
, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6 Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1 Output: []
Example 3:
Input: head = [7,7,7,7], val = 7 Output: []
Constraints:
- The number of nodes in the list is in the range
[0, 104]
. 1 <= Node.val <= 50
0 <= k <= 50
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
解题思路:
借助dummy node。
这个题用 dummy node 的用意在于包括 head 节点在内,都有可能是需要被删除的点,
使得从头节点就是要删除的节点和中间要删除的,可以用相同的处理方式
class Solution { public ListNode removeElements(ListNode head, int val) { if(head==null){ return head; } ListNode cur=new ListNode(0); ListNode curHead=cur; cur.next=head; while(cur.next!=null){ if(cur.next.val==val){ cur.next=cur.next.next; }else{ cur=cur.next; } } return curHead.next; } }
class Solution { public ListNode removeElements(ListNode head, int val) { if(head == null) return head; head.next = removeElements(head.next, val); return head.val == val ? head.next : head; } }