-
Notifications
You must be signed in to change notification settings - Fork 1
/
doubly_linked_list.js
77 lines (70 loc) · 1.45 KB
/
doubly_linked_list.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
function Node(data) {
this.data = data;
this.previous = null;
this.next = null;
}
function DoublyLinkedList() {
this._length = 0;
this.head = null;
this.tail = null;
}
DoublyLinkedList.prototype.isEmpty = function() {
return this._length === 0;
};
DoublyLinkedList.prototype.printLinkedList = function() {
if(this.isEmpty()){
console.log("empty list");
} else {
var current = this.head;
while(current.next !== null){
console.log(current.data);
current = current.next;
}
console.log(current.data);
}
};
DoublyLinkedList.prototype.push = function(node) {
switch(this._length) {
case 0:
this.head = node;
this.tail = node;
this._length++;
break;
default:
node.next = this.head;
this.head.previous = node;
this.head = node;
this._length++;
break;
}
};
DoublyLinkedList.prototype.pop = function() {
if(this.isEmpty()){
return -1;
}
var node = this.head;
this.head = node.next;
this.head.previous = null;
node.next = null;
this._length--;
return node;
};
/**********************
** Testing Functions **
**********************/
var ll = new DoublyLinkedList();
ll.printLinkedList();
var a = new Node("a");
var b = new Node("b");
var c = new Node("c");
ll.push(a);
ll.printLinkedList();
console.log("****");
ll.push(b);
ll.printLinkedList();
console.log("****");
ll.push(c);
ll.printLinkedList();
console.log("****");
ll.pop();
ll.printLinkedList();