203. 移除链表元素
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
示例 1:

1 2
| 输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]
|
示例 2:
示例 3:
提示:
- 列表中的节点数目在范围
[0, 104]
内
1 <= Node.val <= 50
0 <= val <= 50
设置虚拟的头节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(-1,head); ListNode cur = head; ListNode pre = dummy; pre.next = head;
while(cur!= null){ if(cur.val == val){ pre.next = cur.next; cur = cur.next; }else{ cur = cur.next; pre = pre.next; } } return dummy.next; } }
|
不设置虚拟头节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public ListNode removeElements(ListNode head, int val) { while (head != null && head.val == val) { head = head.next; } if (head == null) { return head; } ListNode pre = head; ListNode cur = head.next; while (cur != null) { if (cur.val == val) { pre.next = cur.next; } else { pre = cur; } cur = cur.next; } return head; } }
|