File tree Expand file tree Collapse file tree 2 files changed +26
-9
lines changed Expand file tree Collapse file tree 2 files changed +26
-9
lines changed Original file line number Diff line number Diff line change @@ -13,27 +13,32 @@ class LinkedList {
1313
1414 /**
1515 * Add element to the tail
16- * @param data
16+ * @param dataOrNode
1717 * @returns {Node }
1818 */
19- addLast ( data ) {
20- const node = getNode ( data ) ;
19+ addLast ( dataOrNode ) {
20+ let node = getNode ( dataOrNode ) ;
2121 if ( this . head ) {
2222 this . tail . next = node ;
2323 } else {
2424 this . head = node ;
2525 }
26- this . tail = node ;
27- this . length ++ ;
26+
27+ while ( node ) {
28+ this . tail = node ;
29+ this . length ++ ;
30+ if ( ! node . next ) { break ; }
31+ node = node . next ;
32+ }
2833 return node ;
2934 }
3035
3136 /**
3237 * Add element to the head
3338 * @param data
3439 */
35- addFirst ( data ) {
36- const node = getNode ( data ) ;
40+ addFirst ( dataOrNode ) {
41+ const node = getNode ( dataOrNode ) ;
3742 if ( this . head ) {
3843 node . next = this . head ;
3944 } else {
@@ -45,8 +50,8 @@ class LinkedList {
4550 }
4651
4752 // O(1)
48- add ( data ) {
49- return this . addFirst ( data ) ;
53+ add ( dataOrNode ) {
54+ return this . addFirst ( dataOrNode ) ;
5055 }
5156
5257 // O(n)
Original file line number Diff line number Diff line change @@ -20,6 +20,18 @@ describe('LinkedList', function () {
2020 it ( 'should have a size of 4' , function ( ) {
2121 expect ( list . size ( ) ) . to . equal ( 4 ) ;
2222 } ) ;
23+
24+ it ( 'should add nodes and update the tail and size' , function ( ) {
25+ const list2 = new LinkedList ( ) ;
26+ const a = list2 . addLast ( 'a' ) ;
27+ list2 . addLast ( 'b' ) ;
28+ const c = list2 . addLast ( 'c' ) ;
29+
30+ list . addLast ( a ) ;
31+ expect ( list . toString ( ) ) . to . equal ( '1 -> 2 -> 3 -> 4 -> a -> b -> c' ) ;
32+ expect ( list . size ( ) ) . to . equal ( 7 ) ;
33+ expect ( list . tail ) . to . equal ( c ) ;
34+ } ) ;
2335 } ) ;
2436
2537 describe ( '.addFirst' , function ( ) {
You can’t perform that action at this time.
0 commit comments