// 判断是否有环,有返回入口节点,无返回null·
let hasCycle = function(head) {
let set = new Set();
while (head != null) {
if (set.has(head)) {
return head;
} else {
set.add(head)
head = head.next;
}
}
return null;
};
let hasCycle = function(head) {
if(!head || !head.next) {
return false
}
let fast = head.next.next, slow = head.next
while(fast !== slow) {
if(!fast || !fast.next) return false
fast = fast.next.next
slow = slow.next
}
return true
};
链表反转(反转链表)
function reverse(head){
if(!head || !head.next) return head;
var prev = null, cur = head;
while(cur){
// 用于临时存储 cur 后继节点
var next = curr.next;
// 反转 cur 的后继指针
cur.next = prev;
// 变更 prev, cur
prev = cur
cur = next
}
return prev
}
链表倒数第 k 个节点
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var getKthFromEnd = function(head, k) {
let fast = head
let slow = head
let i = 0
while(i++ < k) {
fast = fast.next
}
while(fast) {
fast = fast.next
slow = slow.next
}
return slow
};