检测链表是否在JS中具有循环

时间:2019-01-11 14:49:06

标签: javascript linked-list

当我不能等于两个节点时,如何查看链表在js中是否存在循环?我已经在网上看到了使用快速指针和慢速指针的方法,但这需要我们将快速指针和慢速指针节点等同起来:

class SLLNode{
    constructor(data)
  {
    this.data = data
    this.next = null
  }
}

class ll {
    constructor(data){
        this.head = new SLLNode(data)
    }
}

function hasCycle(l) {
  var head = l.head
  var slow, fast;

  if(!head || !head.next) return false;

    slow = head;
    fast = head;

    if(head.next === head) return true;

    while(fast.next.next) {

      slow = slow.next;
      fast = fast.next.next;

      if(slow ===fast){ return true;}
    }

  return false;
}
var l = new ll(2)

var m = new ll(2)
var my_node1 = new SLLNode(1)

var my_node2 = new SLLNode(2)

var my_node3 = new SLLNode(3)
//assigning head
l.head = my_node1
//connecting linked list
l.head.next=my_node2;
l.head.next.next=my_node3;
l.head.next.next.next=my_node1; //cycle

console.log(hasCycle(l))

当它本来应该是真的时,我一直在弄虚作假。我们如何比较js中的两个节点

0 个答案:

没有答案