@@ -78,38 +78,44 @@ export default class DoublyLinkedList {
78
78
let deletedNode = null ;
79
79
let currentNode = this . head ;
80
80
81
- do {
81
+ while ( currentNode ) {
82
82
if ( this . compare . equal ( currentNode . value , value ) ) {
83
83
deletedNode = currentNode ;
84
84
85
85
if ( deletedNode === this . head ) {
86
+ // If HEAD is going to be deleted...
87
+
86
88
// Set head to second node, which will become new head.
87
89
this . head = deletedNode . next ;
88
90
89
- // Set new head's previous to null
91
+ // Set new head's previous to null.
90
92
if ( this . head ) {
91
93
this . head . previous = null ;
92
94
}
93
95
94
96
// If all the nodes in list has same value that is passed as argument
95
- // then all nodes will get deleted, therefore tail needs to be updated
97
+ // then all nodes will get deleted, therefore tail needs to be updated.
96
98
if ( deletedNode === this . tail ) {
97
99
this . tail = null ;
98
100
}
99
101
} else if ( deletedNode === this . tail ) {
100
- // set tail to second last node, which will become new tail
102
+ // If TAIL is going to be deleted...
103
+
104
+ // Set tail to second last node, which will become new tail.
101
105
this . tail = deletedNode . previous ;
102
106
this . tail . next = null ;
103
107
} else {
108
+ // If MIDDLE node is going to be deleted...
104
109
const previousNode = deletedNode . previous ;
105
110
const nextNode = deletedNode . next ;
111
+
106
112
previousNode . next = nextNode ;
107
113
nextNode . previous = previousNode ;
108
114
}
109
115
}
110
116
111
117
currentNode = currentNode . next ;
112
- } while ( currentNode ) ;
118
+ }
113
119
114
120
return deletedNode ;
115
121
}
@@ -149,16 +155,22 @@ export default class DoublyLinkedList {
149
155
*/
150
156
deleteTail ( ) {
151
157
if ( ! this . tail ) {
158
+ // No tail to delete.
152
159
return null ;
153
- } else if ( this . head === this . tail ) {
160
+ }
161
+
162
+ if ( this . head === this . tail ) {
163
+ // There is only one node in linked list.
154
164
const deletedTail = this . tail ;
155
165
this . head = null ;
156
166
this . tail = null ;
157
167
158
168
return deletedTail ;
159
169
}
160
170
171
+ // If there are many nodes in linked list...
161
172
const deletedTail = this . tail ;
173
+
162
174
this . tail = this . tail . previous ;
163
175
this . tail . next = null ;
164
176
0 commit comments