Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

203. Remove Linked List Elements #263

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

203. Remove Linked List Elements

删除链表中等于给定值 val 的所有节点。

Example

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
Tcdian commented 4 years ago

Solution

/**
 * 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 ground = new ListNode(-1, head);
    let patrol = ground;
    while (patrol !== null && patrol.next !== null) {
        if (patrol.next.val === val) {
            patrol.next = patrol.next.next;
        } else {
            patrol = patrol.next;
        }
    }
    return ground.next;
};