Skip to content

Commit 862dfaf

Browse files
committed
Add singly-linked-lists
1 parent bcc1c91 commit 862dfaf

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
class Node {
2+
constructor(val) {
3+
this.val = val;
4+
this.next = null;
5+
}
6+
}
7+
8+
class SinglyLinkedList {
9+
constructor() {
10+
this.head = null;
11+
this.tail = null;
12+
this.length = 0;
13+
}
14+
15+
push(val) {
16+
const newNode = new Node(val);
17+
if (!this.head) {
18+
this.head = newNode;
19+
this.tail = this.head;
20+
} else {
21+
this.tail.next = newNode;
22+
this.tail = newNode;
23+
}
24+
25+
this.length++;
26+
return this;
27+
}
28+
29+
// traverse() {
30+
// let current = this.head;
31+
// while (current) {
32+
// console.log(current.val);
33+
// current = current.next;
34+
// }
35+
// }
36+
37+
pop() {
38+
if (!this.tail) return undefined;
39+
let current = this.head;
40+
let newTail = current;
41+
while (current.next) {
42+
newTail = current;
43+
current = current.next;
44+
}
45+
46+
this.tail = newTail;
47+
this.tail.next = null;
48+
this.length--;
49+
50+
if (this.length === 0) {
51+
this.head = null;
52+
this.tail = null;
53+
}
54+
55+
return current;
56+
}
57+
}
58+
59+
let element = new SinglyLinkedList();
60+
61+
console.log(element.pop());
62+
console.log(element.pop());
63+
64+
console.log(element.pop());
65+
66+
console.log(element);

0 commit comments

Comments
 (0)