🌗 203. 移除链表元素

吞佛童子2022年6月9日
  • algorithm
  • list
小于 1 分钟

🌗 203. 移除链表元素

难度: 🌗

问题描述

img.png


解法

/**
 * 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) {
        // 思路:
        // 添加虚拟头结点,防止原头结点即是被删除的节点
        ListNode pre = new ListNode(-1);
        pre.next = head;
        ListNode res = pre;
        ListNode cur = head;
        // 遍历
        while(cur != null) {
            if(cur.val == val) {
                // 删除 cur
                ListNode next = cur.next;
                pre.next = next;
                cur = next;
            } else {
                pre = cur;
                cur = cur.next;
            }
        }
        return res.next;
    }
}

输出

img_1.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou