Skip to content

Commit f413302

Browse files
committedDec 28, 2016
linkedlist datastructure
·
1.3.71.0.0
1 parent 934b681 commit f413302

File tree

11 files changed

+58
-27
lines changed

11 files changed

+58
-27
lines changed
 
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

‎ch2/linked-list.js

Lines changed: 0 additions & 27 deletions
This file was deleted.

‎linked-list/linkedlist.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Node {
2+
constructor(data) {
3+
this.data = data;
4+
}
5+
}
6+
7+
class LinkedList {
8+
constructor() {
9+
this.head = null;
10+
}
11+
12+
// O(1)
13+
add(data) {
14+
if(this.head) {
15+
let newHead = new Node(data);
16+
newHead.next = this.head;
17+
this.head = newHead;
18+
} else {
19+
this.head = new Node(data);
20+
}
21+
}
22+
23+
// O(n)
24+
delete(data) {
25+
let n = this.head;
26+
27+
if(n.data === data) {
28+
this.head = this.head.next;
29+
return;
30+
}
31+
32+
// iterate
33+
while(n.next){
34+
if(n.next.data === data) {
35+
n.next = n.next.next;
36+
return;
37+
}
38+
n = n.next;
39+
}
40+
}
41+
}
42+
43+
let list = new LinkedList();
44+
list.add(1);
45+
list.add(2);
46+
list.add(3);
47+
list.add(4);
48+
49+
console.log(list);
50+
51+
list.delete(4);
52+
console.log(list);
53+
54+
list.delete(2);
55+
console.log(list);
56+
57+
list.delete(1);
58+
console.log(list);

0 commit comments

Comments
 (0)
Please sign in to comment.