-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdoubly_list.js
103 lines (85 loc) · 2.5 KB
/
doubly_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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
function Node(value) {
this.data = value;
this.previous = null;
this.next = null;
}
function DoublyList() {
this._length = 0;
this.head = null;
this.tail = null;
}
DoublyList.prototype.add = function(value) {
var node = new Node(value);
if (this._length === 0) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
node.previous = this.tail;
this.tail = node;
}
this._length++;
return node;
};
DoublyList.prototype.searchNodeAt = function(position) {
var currentNode = this.head,
length = this._length,
count = 1,
message = {failure: "Failure: non-existent node in this list."};
// 1st use-case: an invalid position
if (length === 0 || position < 1 || position > length) {
throw new Error(message.failure);
}
// 2nd use-case: a valid position
while (count < position) {
currentNode = currentNode.next;
count++;
}
return currentNode;
};
DoublyList.prototype.remove = function(position) {
var currentNode = this.head,
length = this._length,
count = 1,
message = {failure: "Failure: non-existent node in this list."
},
beforeNodeToDelete = null,
nodeToDelete = null,
deletedNode = null;
// 1st use-case: an invalid position
if (length === 0 || position < 1 || position > length) {
throw new Error(message.failure);
}
// 2nd use-case: the first node is removed
if (position === 1) {
deletedNode = this.head;
this.head = currentNode.next;
// 2nd use-case: there is no second node
if (!this.head) {
this.tail = null;
// 2nd use-case: there is a second node
} else {
this.head.previous = null;
}
// 3rd use-case: the last node is removed
} else if (position === this._length) {
deletedNode = this.tail;
this.tail = this.tail.previous;
this.tail.next = null;
} else {
// 4th use-case: a middle node is removed
while (count < position) {
currentNode = currentNode.next;
count++;
}
beforeNodeToDelete = currentNode.previous;
nodeToDelete = currentNode;
afterNodeToDelete = currentNode.next;
beforeNodeToDelete.next = afterNodeToDelete;
afterNodeToDelete.previous = beforeNodeToDelete;
deletedNode = nodeToDelete;
nodeToDelete = null;
}
this._length--;
return deletedNode;
};