剑指offer18 删除链表节点
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点,返回删除后的链表的头节点。
1、双指针
var deleteNode = function(head, val) {
if(!head) return null
if(head.val == val) return head.next
let first = null, last = head
while(last.val != val){
first = last
last = last.next
}
first.next = last.next
return head
};
时间复杂度O(n) 空间复杂度O(1)
2、单指针
var deleteNode = function(head, val) {
if(!head) return null
if(head.val == val) return head.next
let cur = head
while(cur){
if(cur.next.val == val){
cur.next = cur.next.next
return head
}
cur = cur.next
}
};
时间复杂度O(n) 空间复杂度O(1)