链表和数组
[1,2,3,4,5] 1=>2=>3
数组
数据结构的增删改查
arr[0] arr[1] 随机访问O(1)
数组的新增元素复杂度是O(n)
链表
1=>2=>3=>4
随机访问的负复杂度是O(n)
删除和插入元素复杂度是O1
leetcode 203. 移除链表元素
var removeElements = function(head, val) {
// 哨兵 =>1 =>2 =>3
let ele = {
next: head
}
let p = ele
console.log(p.next)
while(p.next){
if(p.next.val === val){
p.next = p.next.next
}else{
p = p.next
}
}
return ele.next
};
leetcode 141. 环形链表
var hasCycle = function(head) {
let cache = new Set()
while(head){
// console.log(cache)
if(cache.has(head)){
return true
}else{
cache.add(head)
}
head = head.next
}
return false
// 双指针思路
// let slow = head
// let fast = head
// while(fast && fast.next){
// fast = fast.next.next
// slow = slow.next
// if(slow === fast) return true
// }
// return false
};