Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b150c93

Browse files
author
Manjunath
committed
check loop and count nodes in LL
1 parent a5b988e commit b150c93

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Node {
2+
constructor(data) {
3+
this.data = data;
4+
this.next = null;
5+
}
6+
}
7+
8+
function countNodesInLoop(list) {
9+
let temp = list;
10+
let count = 1;
11+
while (temp.next != list) {
12+
count++;
13+
temp = temp.next;
14+
}
15+
return count;
16+
}
17+
18+
function checkLoopAndCountNodes(head) {
19+
if (head == null) return 0;
20+
let fastPointer = head,
21+
slowPointer = head;
22+
while (slowPointer && fastPointer && fastPointer.next) {
23+
slowPointer = slowPointer.next;
24+
fastPointer = fastPointer.next.next;
25+
if (slowPointer == fastPointer) return countNodesInLoop(slowPointer);
26+
}
27+
return 0;
28+
}
29+
30+
function displayList(list) {
31+
let output = ''
32+
while (list != null) {
33+
output += list.data + ' ';
34+
list = list.next;
35+
}
36+
console.log(output);
37+
}
38+
39+
let list = new Node(1);
40+
list.next = new Node(2);
41+
list.next.next = new Node(3);
42+
list.next.next.next = new Node(4);
43+
list.next.next.next.next = new Node(5);
44+
list.next.next.next.next.next = list.next;
45+
let countNodes = checkLoopAndCountNodes(list);
46+
console.log(countNodes != 0 ? " Loop exists and Number of Nodes in Loop is " + countNodes : "Loop doesn't exists");

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /