Skip to content

Commit 0f66fb0

Browse files
author
Tony K Tan
committed
(attempt) 2.7
1 parent ff6f965 commit 0f66fb0

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
var LinkedList = require('./../util/LinkedList');
2+
3+
var peek = function(stack) {
4+
return stack[stack.length - 1];
5+
};
6+
7+
var intersection = function(head1, head2) {
8+
var stack1 = [];
9+
var stack2 = [];
10+
11+
while (head1 !== null) {
12+
stack1.push(head1);
13+
head1 = head1.next;
14+
}
15+
16+
while (head2 !== null) {
17+
stack2.push(head2);
18+
head2 = head2.next;
19+
}
20+
21+
// if not intersecting return undefined.
22+
if (stack1.length === 0 || stack2.length === 0) {
23+
return undefined;
24+
} else if (peek(stack1) !== peek(stack2)) {
25+
return undefined;
26+
} else {
27+
var intersect;
28+
while (peek(stack1) === peek(stack2)) {
29+
intersect = peek(stack1);
30+
stack1.pop();
31+
stack2.pop();
32+
}
33+
return intersect;
34+
}
35+
// if intersecting, return intersecting node.
36+
};
37+
38+
/* TEST */
39+
40+
var a = new LinkedList('a');
41+
var b = new LinkedList('b');
42+
var c = new LinkedList('c');
43+
var d = new LinkedList('d');
44+
var e = new LinkedList('e');
45+
var f = new LinkedList('f');
46+
var g = new LinkedList('g');
47+
var h = new LinkedList('h');
48+
49+
a.next = b;
50+
b.next = c;
51+
c.next = d;
52+
d.next = e;
53+
e.next = f;
54+
f.next = g;
55+
g.next = h;
56+
57+
var a1 = new LinkedList('a1');
58+
var b1 = new LinkedList('b1');
59+
var c1 = new LinkedList('c1');
60+
61+
a1.next = b1;
62+
b1.next = c1;
63+
c1.next = d;
64+
65+
var intersectNode = intersection(a, a1);
66+
67+
console.log(intersectNode.value);

lib/chapter2/util/LinkedList.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
module.exports = function(value) {
2+
this.value = value;
3+
this.next = null;
4+
};

lib/chapter2/util/printList.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
module.exports = function(head) {
2+
while (head !== null) {
3+
console.log(head.value);
4+
head = head.next;
5+
}
6+
};

0 commit comments

Comments
 (0)