@@ -112,17 +112,35 @@ class singlyLinkedList {
112
112
}
113
113
if ( index === this . length ) {
114
114
this . push ( newNode ) ;
115
- } else if ( index === 0 ) {
115
+ return true ;
116
+ }
117
+ if ( index === 0 ) {
116
118
this . unshift ( newNode ) ;
117
- } else {
118
- const prev = this . get ( index - 1 ) ;
119
- const temp = prev . next ;
120
- prev . next = newNode ;
121
- newNode . next = temp ;
119
+ return true ;
122
120
}
121
+ const prev = this . get ( index - 1 ) ;
122
+ const temp = prev . next ;
123
+ prev . next = newNode ;
124
+ newNode . next = temp ;
123
125
this . length ++ ;
124
126
return true ;
125
127
}
128
+ remove ( index ) {
129
+ if ( index < 0 || index >= this . length ) {
130
+ return undefined ;
131
+ }
132
+ if ( index === this . length - 1 ) {
133
+ return this . pop ( ) ;
134
+ }
135
+ if ( index === 0 ) {
136
+ this . shift ( ) ;
137
+ }
138
+ const prev = this . get ( index - 1 ) ;
139
+ const removed = prev . next ;
140
+ prev . next = removed . next ;
141
+ this . length -- ;
142
+ return removed ;
143
+ }
126
144
}
127
145
128
146
// const first = new Node("hi");
@@ -138,15 +156,17 @@ list.push("hadis");
138
156
list . push ( "how" ) ;
139
157
list . push ( "are" ) ;
140
158
list . push ( "you" ) ;
141
- console . log ( ' traverse list: ' ) ;
159
+ console . log ( " traverse list: " ) ;
142
160
list . traverse ( ) ;
143
- console . log ( ' Deleted Node: ' , list . pop ( ) ) ;
144
- console . log ( ' print List: ' , list ) ;
145
- console . log ( ' Shifted Node: ' , list . shift ( ) ) ;
146
- console . log ( ' print List: ' , list ) ;
147
- list . unshift ( ' welcome' ) ;
148
- console . log ( ' print List: ' , list ) ;
161
+ console . log ( " Deleted Node: " , list . pop ( ) ) ;
162
+ console . log ( " print List: " , list ) ;
163
+ console . log ( " Shifted Node: " , list . shift ( ) ) ;
164
+ console . log ( " print List: " , list ) ;
165
+ list . unshift ( " welcome" ) ;
166
+ console . log ( " print List: " , list ) ;
149
167
console . log ( list . get ( 0 ) ) ;
150
168
console . log ( list . get ( 3 ) ) ;
151
- list . set ( 'where ' , 2 ) ;
152
- list . insert ( 'test' , 2 ) ;
169
+ list . set ( "where " , 2 ) ;
170
+ list . insert ( "test" , 2 ) ;
171
+ list . remove ( 1 ) ;
172
+ list . traverse ( ) ;
0 commit comments