力扣203-移除链表元素【学习笔记】

21 阅读1分钟

问题: 给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

难点:

删除的是头结点?

var removeElements = function(head, val) {
    while(head!=null&&head.val==val){
        head = head.next
    }
    while(head==null){
        return head
    }
    let cur = head.next
    let pre = head
    while(cur){
        if(cur.val!=val){
            cur = cur.next
            pre = pre.next
        }else{
            pre.next = cur.next
            cur =pre.next
        }
    }
    return head
};