判定链表中是否含有环

image-20210424203503951.png

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val) {
  4. * this.val = val;
  5. * this.next = null;
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} head
  10. * @return {boolean}
  11. */
  12. var hasCycle = function(head) {
  13. if(head===null || head.next===null){
  14. return false;
  15. }
  16. let slow = head,fast = head;
  17. while(fast!=null){
  18. slow = slow?.next;
  19. fast = fast?.next?.next;
  20. if(slow === fast){
  21. return true;
  22. }
  23. }
  24. return false;
  25. };

环形链表位置

算法思路:
image-20210424203515743.png

  1. var detectCycle = function(head) {
  2. if (head === null) {
  3. return null;
  4. }
  5. let slow = head, fast = head;
  6. while (fast !== null) {
  7. slow = slow.next;
  8. if (fast.next !== null) {
  9. fast = fast.next.next;
  10. } else {
  11. return null;
  12. }
  13. if (fast === slow) {
  14. let ptr = head;
  15. while (ptr !== slow) {
  16. ptr = ptr.next;
  17. slow = slow.next;
  18. }
  19. return ptr;
  20. }
  21. }
  22. return null;
  23. };

寻找链表的倒数第 n 个元素

image-20210424205645614.png

  1. var removeNthFromEnd = function(head, n) {
  2. let fast, slow;
  3. fast = slow = head;
  4. while(n !== 0){
  5. fast = fast?.next;
  6. n--;
  7. }
  8. if(fast === null){
  9. return head.next;
  10. }
  11. while(fast!==null && fast.next !== null){
  12. fast = fast?.next;
  13. slow = slow?.next;
  14. }
  15. slow.next = slow.next.next;
  16. return head;
  17. };