-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2_linked_list_intersection.js
More file actions
81 lines (70 loc) · 1.7 KB
/
2_linked_list_intersection.js
File metadata and controls
81 lines (70 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
function linkedListIntersection(list1, list2) {
let currNode1 = list1.head;
let currNode2 = list2.head;
let seenNodes = {};
while (currNode1 || currNode2) {
if (currNode2) {
if (seenNodes.hasOwnProperty(currNode2.value)) return currNode2;
seenNodes[currNode2.value] = true;
currNode2 = currNode2.next;
}
if (currNode1) {
if (seenNodes.hasOwnProperty(currNode1.value)) return currNode1;
seenNodes[currNode1.value] = true;
currNode1 = currNode1.next
}
}
return null;
}
// ----------------------------------------
// Given: Singly Linked List - Do Not Edit!
// ----------------------------------------
class Node {
constructor(val) {
this.value = val;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
addToTail(val) {
const newNode = new Node(val);
if (!this.head) {
this.head = newNode;
} else {
this.tail.next = newNode;
}
this.tail = newNode;
this.length++;
return this;
}
get(index) {
if (index < 0 || index >= this.length) return null;
let counter = 0;
let current = this.head;
while (counter !== index) {
current = current.next;
counter++;
}
return current;
}
}
// --------------------------------------
// Helper For Testing Only - Do Not Edit!
// --------------------------------------
var stringify = function(list) {
var result = [];
while(list !== null) {
result.push(list.value);
list = list.next;
}
return result.join("");
}
exports.Node = Node;
exports.LinkedList = LinkedList;
exports.linkedListIntersection = linkedListIntersection;
exports.stringify = stringify;