链表-移除链表元素

69 阅读1分钟

简单题重拳出击 中等题溜之大吉

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

对应力扣203题 迭代实现

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */

var removeElements = function(head, val) {
    const ret = new ListNode(0, head);
    let curr = ret;
    while(curr.next) {
        if (curr.next.val === val) {
            curr.next = curr.next.next;
            continue;
        }
        curr = curr.next;
    }
    return ret.next;
};

题解中递归实现则是更简单

var removeElements = function(head, val) {
    if (head === null) {
            return head;
        }
        head.next = removeElements(head.next, val);
        return head.val === val ? head.next : head;
};