-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedlist.js
90 lines (79 loc) · 1.44 KB
/
linkedlist.js
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
82
83
84
85
86
87
88
89
90
class ListNode {
constructor(x) {
this.value = x;
this.next = null;
}
}
class LinkedList {
constructor() {
this._length = 0;
this.head = null;
}
add(value) {
let node = new ListNode(value);
let current = this.head;
if (!current) {
this.head = node;
this._length++;
return node;
}
while (current.next) {
current = current.next;
}
current.next = node;
this._length++;
return node;
}
remove(value) {
let curr = this.head;
let p = curr;
while (p.next) {
if (p.next.value === value) {
const next = p.next;
p.next = next.next;
}
else {
p = p.next;
}
}
this.head = curr;
}
getElementAt(pos) {
let curr = this.head;
let i = 0;
if (pos < 0) {
return this.head.value;
}
while (curr) {
if (pos === i) {
return curr.value;
}
i++;
curr = curr.next;
}
return curr.value;
}
size() {
return this._length;
}
printElements() {
let array = [];
let curr = this.head;
while (curr) {
array.push(curr.value);
curr = curr.next;
}
return array;
}
}
// How to use it
let list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
console.log(list.printElements());
list.remove(3);
console.log(list.printElements());
console.log(list.getElementAt(2));