移除链表元素
https://leetcode.cn/problems/remove-linked-list-elements/ (opens new window)
# 迭代版本
/**
* 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) {
// 处理开头等于val
while(head !== null && head.val == val){
head = head.next
}
// 如果head 为空,返回 head
if(head === null)
return head
// 如果 head 不为空,则继续遍历 head
let prev = head
while(prev.next != null){
if(prev.next.val == val)
prev.next = prev.next.next
else
prev = prev.next
}
return head
};
/**
* 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 dummyHead = new ListNode(0)
dummyHead.next = head
// cur指向 dummyHead
let cur = dummyHead
// 遍历的是 cur.next
while(cur.next != null){
if(cur.next.val == val){
// 如果 cur.next.val == val, 那么 将 cur.next 指向 cur.next.next, 遍历的还是 cur.next
cur.next = cur.next.next
}else{
// 如果 不等, 那么 cur 指向 cur.next
cur = cur.next
}
}
return dummyHead.next
};
# 递归
var removeElements = function(head, val) {
// 递归解法
// 如果head 为空, 直接返回
if( head == null)
return head
// 递归解法关注的是头节点的结果和剩下节点的结果
// 在这里我不会直接求解剩下节点的结果
// result 是剩下节点的结果, 暂时放入递归函数
let result = removeElements(head.next, val)
if(head.val == val)
// 头节点的值等于 val 那么删除该节点
return result
else{
// 头节点的值!= val, 那么返回结果是 head+ result
head.next = result
return head
}
};