Its giving TLE due to insertion part, even though insertion is in O(1). Then what is wrong with insertion
Tle with this insertion
In the codes of linked list, since you have to build the list, it is always recommend to use the logic of insertAtTail, rather than the approach you have used in your code.