@@ -17,21 +17,20 @@ class LinkedList {
1717 * @param {any } value
1818 */
1919 addLast ( value ) {
20- const node = new Node ( value ) ;
20+ const newNode = new Node ( value ) ;
2121
2222 if ( this . first ) {
23- let currentNode = this . first ;
24- node . previous = this . last ;
25- this . last . next = node ;
26- this . last = node ;
23+ newNode . previous = this . last ;
24+ this . last . next = newNode ;
25+ this . last = newNode ;
2726 } else {
28- this . first = node ;
29- this . last = node ;
27+ this . first = newNode ;
28+ this . last = newNode ;
3029 }
3130
3231 this . size ++ ;
3332
34- return node ;
33+ return newNode ;
3534 }
3635
3736 /**
@@ -122,15 +121,15 @@ class LinkedList {
122121 * Remove the nth element from the list. Starting with 0
123122 * Returns value if found or undefined if it was not found
124123 * Runtime: O(n)
125- * @param {any } nth
124+ * @param {any } index
126125 */
127- removeAt ( nth ) {
128- if ( nth === 0 ) {
126+ removeAt ( index ) {
127+ if ( index === 0 ) {
129128 return this . removeFirst ( ) ;
130129 }
131130
132- for ( let current = this . first , index = 0 ; current ; index ++ , current = current . next ) {
133- if ( index === nth ) {
131+ for ( let current = this . first , i = 0 ; current ; i ++ , current = current . next ) {
132+ if ( i === index ) {
134133 if ( ! current . next ) { // if it doesn't have next it means that it is the last
135134 return this . removeLast ( ) ;
136135 }
@@ -141,10 +140,38 @@ class LinkedList {
141140 }
142141 }
143142
143+ /**
144+ * Insert new element on the given position
145+ * Returns index if it failed to insert element (index out of bounds), otherwise undefined
146+ * @param {any } value new node's value
147+ * @param {Number } index position to insert element
148+ */
149+ add ( value , index = 0 ) {
150+ if ( index === 0 ) {
151+ return this . addFirst ( value ) ;
152+ }
153+
154+ for ( let current = this . first , i = 0 ; i <= this . size ; i ++ , current = ( current && current . next ) ) {
155+ if ( i === index ) {
156+ if ( i === this . size ) { // if it doesn't have next it means that it is the last
157+ return this . addLast ( value ) ;
158+ }
159+ const newNode = new Node ( value ) ;
160+ newNode . previous = current . previous ;
161+ newNode . next = current ;
162+
163+ current . previous . next = newNode ;
164+ if ( current . next ) { current . next . previous = newNode ; }
165+ this . size ++ ;
166+ return newNode ;
167+ }
168+ }
169+ }
170+
144171}
145172
146173// Aliases
147- LinkedList . prototype . add = LinkedList . prototype . push = LinkedList . prototype . addLast ;
174+ LinkedList . prototype . push = LinkedList . prototype . addLast ;
148175LinkedList . prototype . remove = LinkedList . prototype . pop = LinkedList . prototype . removeLast ;
149176LinkedList . prototype . unshift = LinkedList . prototype . addFirst ;
150177LinkedList . prototype . shift = LinkedList . prototype . removeFirst ;
0 commit comments