Skip to content

Commit 8c9ed88

Browse files
committed
--update: added removeFromEnd()
1 parent 908c0d9 commit 8c9ed88

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/_DataStructures_/LinkedList/LinkedList.test.js

+9
Original file line numberDiff line numberDiff line change
@@ -67,5 +67,14 @@ describe('Data Structures: Linked Lists', () => {
6767
expect(list.removeFromBeginning()).toEqual(16);
6868
expect(list.length()).toEqual(1);
6969
});
70+
71+
it('Should remove element at last using list.removeFromEnd()', () => {
72+
expect(list.removeFromEnd()).toEqual(null);
73+
74+
list.addAtBeginning(15);
75+
list.addAtBeginning(14);
76+
expect(list.removeFromEnd()).toEqual(15);
77+
expect(list.length()).toEqual(1);
78+
});
7079
});
7180
});

src/_DataStructures_/LinkedList/index.js

+14
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,20 @@ class LinkedList {
5555
this.head = this.head.next;
5656
return temp.data;
5757
}
58+
59+
removeFromEnd() {
60+
if (!this.head) {
61+
return null;
62+
}
63+
let address = this.head;
64+
65+
while (address.next.next) {
66+
address = address.next;
67+
}
68+
const { data } = address.next;
69+
address.next = null;
70+
return data;
71+
}
5872
}
5973

6074
module.exports = { LinkedList, Node };

0 commit comments

Comments
 (0)