Skip to content

Commit 17cb038

Browse files
committed
Add JavaScript doubly linked list
1 parent fd5a9e5 commit 17cb038

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
node_modules
2+
*.log
3+
.DS_Store

JavaScript/1-doubly.js

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
'use strict';
2+
3+
function LinkedList() {
4+
this.first = null;
5+
this.last = null;
6+
this.length = 0;
7+
}
8+
9+
LinkedList.prototype.push = function(data) {
10+
let node = new Node(this, data);
11+
node.prev = this.last;
12+
if (this.length === 0) this.first = node;
13+
else this.last.next = node;
14+
this.last = node;
15+
this.length++;
16+
return node;
17+
};
18+
19+
LinkedList.prototype.pop = function() {
20+
if (this.length > 0) {
21+
let node = this.last;
22+
this.last = node.prev;
23+
node.list = null;
24+
node.prev = null;
25+
node.next = null;
26+
this.length--;
27+
return node.data;
28+
}
29+
};
30+
31+
function Node(list, data) {
32+
this.list = list;
33+
this.data = data;
34+
this.prev = null;
35+
this.next = null;
36+
}
37+
38+
let list = new LinkedList();
39+
list.push({ name: 'first' });
40+
list.push({ name: 'second' });
41+
list.push({ name: 'third' });
42+
43+
console.dir(list.pop());
44+
console.dir(list.pop());
45+
console.dir(list.pop());
46+
console.dir(list.pop());
47+
48+
list.push({ name: 'uno' });
49+
list.push({ name: 'due' });
50+
console.dir(list.pop());
51+
list.push({ name: 'tre' });
52+
console.dir(list.pop());
53+
console.dir(list.pop());

0 commit comments

Comments
 (0)