AlgoDaily Solution
1var assert = require('assert');
2
3function detectLoop(head) {
4 let pointer1, pointer2;
5 pointer1 = head;
6 pointer2 = head;
7
8 while (pointer2.next.next) {
9 pointer1 = pointer1.next;
10 pointer2 = pointer2.next.next;
11
12 if (pointer1 == pointer2) {
13 return true;
14 }
15 }
16 return false;
17}
18
19function Node(val) {
20 this.val = val;
21 this.next = null;
22}
23
24function LinkedListNode(val) {
25 this.val = val;
26 this.next = null;
27}
28
29var list1 = new LinkedListNode(3);
30var nodes1 = [4, 5, 6, 7, 8, 9, 10];
31createNodes(list1, nodes1);
32
33var list2 = new LinkedListNode(1);
34var nodes2 = [2, 3, 4, 5, 6, 7, 8];
35createNodes(list2, nodes2);
36
37function createNodes(head, nodes) {
38 for (let i = 0; i < nodes.length; i++) {
39 var newNode = new LinkedListNode(nodes[i]);
40 head.next = newNode;
41 head = newNode;
42 }
43}
44
45try {
46 list1.next.next.next.next.next.next = list1.next.next;
47 assert.equal(detectLoop(list1), true);
48
49 console.log(
50 'PASSED: Assuming list1.head.next.next.next.next = list1.head, we can detect an artificial loop in the linked list'
51 );
52} catch (err) {
53 console.log(err);
54}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
62
var assert = require('assert');
function detectLoop(head) {
// Fill in this method
return head;
}
class LinkedListNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
const list1 = new LinkedListNode(3);
const nodes = [4, 5, 6, 7, 8, 9, 10];
let head = list1;
for (let i = 0; i < nodes.length; i++) {
const newNode = new LinkedListNode(nodes[i]);
head.next = newNode;
head = newNode;
}
list1.next.next.next.next.next.next = list1.next.next;
console.log(detectLoop(list1));
function Node(val) {
this.val = val;
OUTPUT
Results will appear here.