Skip to content

Commit cf04c80

Browse files
author
Manjunath
committed
find pairs sum of x
1 parent 6641963 commit cf04c80

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
'use strict';
2+
class Node {
3+
constructor(data) {
4+
this.data = data;
5+
this.next = this.previous = null;
6+
}
7+
}
8+
9+
function findPairsSumOfX(list, x) {
10+
let count = 0;
11+
let head = list,
12+
tail = list.previous;
13+
while (head != tail) {
14+
let sum = head.data + tail.data;
15+
if (sum == x) {
16+
head = head.next;
17+
tail = tail.previous;
18+
count++;
19+
continue;
20+
} else if (sum > x) tail = tail.previous;
21+
else if (sum < x) head = head.next;
22+
}
23+
return count;
24+
}
25+
26+
function displayList(list) {
27+
let output = ''
28+
let temp = list;
29+
while (temp.next != list) {
30+
output = output + temp.data + ' ';
31+
temp = temp.next;
32+
}
33+
output = output + temp.data + ' ';
34+
console.log(output);
35+
}
36+
37+
let list = new Node(1);
38+
list.next = new Node(2);
39+
list.next.previous = list;
40+
41+
list.next.next = new Node(3);
42+
list.next.next.previous = list.next;
43+
44+
list.next.next.next = new Node(4);
45+
list.next.next.next.previous = list.next.next;
46+
47+
list.next.next.next.next = new Node(5);
48+
list.next.next.next.next.previous = list.next.next.next;
49+
50+
list.next.next.next.next.next = new Node(6);
51+
list.next.next.next.next.next.previous = list.next.next.next.next;
52+
53+
list.previous = list.next.next.next.next.next;
54+
list.next.next.next.next.next.next = list;
55+
displayList(list);
56+
57+
let x = 5;
58+
console.log('Pairs of ' + x + ' = ' + findPairsSumOfX(list, x));

0 commit comments

Comments
 (0)