-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy path6-doubly-proto.js
55 lines (47 loc) · 1.07 KB
/
6-doubly-proto.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
'use strict';
function LinkedList() {
this.first = null;
this.last = null;
this.length = 0;
}
LinkedList.prototype.push = function(data) {
const node = new Node(this, data);
node.prev = this.last;
if (this.length === 0) this.first = node;
else this.last.next = node;
this.last = node;
this.length++;
return node;
};
LinkedList.prototype.pop = function() {
if (this.length === 0) return null;
const node = this.last;
this.last = node.prev;
this.last.next = null;
node.list = null;
node.prev = null;
node.next = null;
this.length--;
return node.data;
};
function Node(list, data) {
this.list = list;
this.data = data;
this.prev = null;
this.next = null;
}
// Usage
const list = new LinkedList();
list.push({ name: 'first' });
list.push({ name: 'second' });
list.push({ name: 'third' });
console.dir(list.pop());
console.dir(list.pop());
console.dir(list.pop());
console.dir(list.pop());
list.push({ name: 'uno' });
list.push({ name: 'due' });
console.dir(list.pop());
list.push({ name: 'tre' });
console.dir(list.pop());
console.dir(list.pop());