In an interview I was asked to write an insert function for linked list in such a way that after the insertion, the element towards the head side of the inserted element should be greater and the tail side should be smaller when compared to inserted element.
I had implemented the following steps in my code:
- initially sort the linked list in descending order.
- get the element.
- insert the element in such way that the linked list will be in descending order even after insertion.
But I was told that my way was not efficient.
Please let me know if there are efficient way to achieve the same.
Sort is an
O(n log n)operation. If you read the question carefully they never say the list should be sorted, so don’t do the sort operation. What you should do instead is start with a new list with only your element, then for each element of the original list append it either to the front (if greater than the new element) or otherwise at the back.