File tree Expand file tree Collapse file tree 1 file changed +33
-6
lines changed Expand file tree Collapse file tree 1 file changed +33
-6
lines changed Original file line number Diff line number Diff line change @@ -3,16 +3,43 @@ const Node = require('./node');
33class LinkedList {
44 constructor ( ) {
55 this . head = null ;
6+ this . tail = null ;
67 }
78
8- // O(1)
9- add ( data ) {
10- const newHead = new Node ( data ) ;
9+ /**
10+ * Add element to the tail
11+ * @param data
12+ * @returns {Node }
13+ */
14+ addLast ( data ) {
15+ const node = new Node ( data ) ;
16+ if ( this . head ) {
17+ this . tail . next = node ;
18+ } else {
19+ this . head = node ;
20+ }
21+ this . tail = node ;
22+ return node ;
23+ }
24+
25+ /**
26+ * Add element to the head
27+ * @param data
28+ */
29+ addFirst ( data ) {
30+ const node = new Node ( data ) ;
1131 if ( this . head ) {
12- newHead . next = this . head ;
32+ node . next = this . head ;
33+ } else {
34+ this . tail = node ;
1335 }
14- this . head = newHead ;
15- return newHead ;
36+ this . head = node ;
37+ return node ;
38+ }
39+
40+ // O(1)
41+ add ( data ) {
42+ return this . addFirst ( data ) ;
1643 }
1744
1845 // O(n)
You can’t perform that action at this time.
0 commit comments