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 {
13
13
14
14
/**
15
15
* Add element to the tail
16
- * @param data
16
+ * @param dataOrNode
17
17
* @returns {Node}
18
18
*/
19
- addLast(data ){
20
- const node = getNode(data );
19
+ addLast(dataOrNode ){
20
+ let node = getNode(dataOrNode );
21
21
if(this.head) {
22
22
this.tail.next = node;
23
23
} else {
24
24
this.head = node;
25
25
}
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
+ }
28
33
return node;
29
34
}
30
35
31
36
/**
32
37
* Add element to the head
33
38
* @param data
34
39
*/
35
- addFirst(data ) {
36
- const node = getNode(data );
40
+ addFirst(dataOrNode ) {
41
+ const node = getNode(dataOrNode );
37
42
if(this.head) {
38
43
node.next = this.head;
39
44
} else {
@@ -45,8 +50,8 @@ class LinkedList {
45
50
}
46
51
47
52
// O(1)
48
- add(data ) {
49
- return this.addFirst(data );
53
+ add(dataOrNode ) {
54
+ return this.addFirst(dataOrNode );
50
55
}
51
56
52
57
// O(n)
Original file line number Diff line number Diff line change @@ -20,6 +20,18 @@ describe('LinkedList', function () {
20
20
it('should have a size of 4', function () {
21
21
expect(list.size()).to.equal(4);
22
22
});
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
+ });
23
35
});
24
36
25
37
describe('.addFirst', function () {
You can’t perform that action at this time.
0 commit comments