date created | date modified |
---|---|
2022-08-18, 11:29:22 |
2022-08-18, 11:39:01 |
- alias:
- parent :: [[algo-删除链表中的元素]]
- siblings ::
- child ::
- refs: https://leetcode.cn/problems/remove-linked-list-elements/
- 设置 dummy 节点可以避免删除 head 节点带来的额外处理代码
- 单链表的删除节点操作都需要两个指针:一个 cur 指向当前处理节点,一个 pre 指向前驱结点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
ListNode dummy = new ListNode(0, head);
ListNode cur = head;
ListNode pre = dummy;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
// pre 保持不动
} else {
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}
}