Skip to content

Latest commit

 

History

History
48 lines (43 loc) · 1.19 KB

203. 移除链表元素.md

File metadata and controls

48 lines (43 loc) · 1.19 KB
date created date modified
2022-08-18, 11:29:22
2022-08-18, 11:39:01

Meta


  1. 设置 dummy 节点可以避免删除 head 节点带来的额外处理代码
  2. 单链表的删除节点操作都需要两个指针:一个 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;
    }
}