判定链表中是否含有环

/*** Definition for singly-linked list.* function ListNode(val) {* this.val = val;* this.next = null;* }*//*** @param {ListNode} head* @return {boolean}*/var hasCycle = function(head) {if(head===null || head.next===null){return false;}let slow = head,fast = head;while(fast!=null){slow = slow?.next;fast = fast?.next?.next;if(slow === fast){return true;}}return false;};
环形链表位置
算法思路:
var detectCycle = function(head) {if (head === null) {return null;}let slow = head, fast = head;while (fast !== null) {slow = slow.next;if (fast.next !== null) {fast = fast.next.next;} else {return null;}if (fast === slow) {let ptr = head;while (ptr !== slow) {ptr = ptr.next;slow = slow.next;}return ptr;}}return null;};
寻找链表的倒数第 n 个元素

var removeNthFromEnd = function(head, n) {let fast, slow;fast = slow = head;while(n !== 0){fast = fast?.next;n--;}if(fast === null){return head.next;}while(fast!==null && fast.next !== null){fast = fast?.next;slow = slow?.next;}slow.next = slow.next.next;return head;};
