We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
since I wasn't able to get the JavaScript to work, and sounds like others have experienced it as well, here's a code you can run in dev console or jsfiddle to see how linked list with cycle and non-cycle can be worked out
classNode{constructor(value){this.value=value;this.next=null;}}classLinkedList{constructor(){this.head=null;}add(value){letnewNode=newNode(value);letiter=this.head;if(iter===null){this.head=newNode;}else{while(iter.next!==null){iter=iter.next;}iter.next=newNode;}}}letnonCycledLinkedList=newLinkedList();letcycledLinkedList=newLinkedList();functioncreateNonCycledLinkedList(){nonCycledLinkedList.add(1);nonCycledLinkedList.add(2);nonCycledLinkedList.add(3);nonCycledLinkedList.add(4);nonCycledLinkedList.add(5);nonCycledLinkedList.add(6);}functioncreateCycledLinkedList(){cycledLinkedList.add(1);cycledLinkedList.add(2);cycledLinkedList.add(3);cycledLinkedList.add(4);cycledLinkedList.add(5);cycledLinkedList.add(6);lettail=cycledLinkedList.head;letcycle=cycledLinkedList.head;while(tail.next!==null){tail=tail.next;}constcyclePos=3;for(leti=0;i<cyclePos;i++){cycle=cycle.next;}tail.next=cycle;}createNonCycledLinkedList();createCycledLinkedList();functionisCycle(list){letrabbit=list.head;letturtle=list.head;rabbit=rabbit.next.next;while(turtle&&rabbit&&rabbit.value!==turtle.value){rabbit=rabbit.next.next;turtle=turtle.next;}if(!rabbit||!turtle){returnconsole.log("the linked list is not cycle")}if(rabbit.value===turtle.value){returnconsole.log("the linked list is cycle");}}isCycle(nonCycledLinkedList);isCycle(cycledLinkedList);
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Cycle Detection
You are viewing a single comment's thread. Return to all comments →
since I wasn't able to get the JavaScript to work, and sounds like others have experienced it as well, here's a code you can run in dev console or jsfiddle to see how linked list with cycle and non-cycle can be worked out