0

我正在尝试在我创建的链接列表中检测一个循环(我正在练习面试问题)。我理解弗洛伊德的龟兔算法所涉及的逻辑,但该函数总是返回错误......

这是我的链接列表:

class LinkedList {
  constructor() {
    this.length = 0;
    this.head = null;
  }
  insert(index, value) {
    if (index < 0 || index > this.length) {
       throw new Error("Index error");
    }
    const newNode = {
       value
    };
    if (index == 0) {
      newNode.next = this.head;
      this.head = newNode;
    } else {
      const node = this._find(index - 1);
      newNode.next = node.next;
      node.next = newNode;
    }
    this.length++;
  }
  ...
}

//Inserting values
const linkedList = new LinkedList();
linkedList.insert(0, 12);
linkedList.insert(1, 24);
linkedList.insert(2, 65);
linkedList.insert(3, 23);
linkedList.insert(4, 9);
linkedList.insert(5, 7);
linkedList.insert(6, 13);
linkedList.insert(7, 65);
linkedList.insert(8, 20);

这是我的循环检测功能,即使有循环它也会返回 false:

 function containsCycle(firstNode) {
   // Start both at beginning
   let slow = firstNode;
   let fast = firstNode;
   // Until end of the list
   while (fast && fast.next) {
     slow = slow.next;
     fast = fast.next.next;
   // fast is about to "lap" slow
     if (fast === slow) {
       return true;
     }
    }
   // fast hit the end of the list
   return false;
 }

//Calling function
containsCycle(linkedList.head);

我只是找不到我的功能有什么问题,而且我越想弄清楚我变得越狭隘......任何指导将不胜感激!

4

1 回答 1

1

每次插入都会创建新节点。例如,您是第 3 和第 8 个节点的值都为 65,但不相等(它们是不同的对象,因此===条件将失败)。更重要的是,它们有不同.next的节点,并且您的迭代器slwofast迭代器在遍历第 8 个元素后不会循环回第 4 个元素。

于 2019-04-23T19:38:11.223 回答