0

What is the time complexity of inserting a node in a sorted linked list in Java? Is there an algorithm with complexity less than O(n)?

willeM_ Van Onsem
481k33 gold badges481 silver badges622 bronze badges
asked Apr 17, 2017 at 16:51
4
  • Usually not, unless there you have references to several nodes in the list. Commented Apr 17, 2017 at 16:52
  • 1
    With only O(1) references into the list (e.g. head + tail), then no. Commented Apr 17, 2017 at 16:54
  • @OliverCharlesworth there is no pointers in Java. Commented Apr 17, 2017 at 16:55
  • 2
    @Omore - NullPointerException disagrees ;) (Didn't notice that this was marked Java...) Commented Apr 17, 2017 at 16:57

1 Answer 1

4

If all you have is a linked links and you're starting from the head, in the worst case you have to iterate over the entire list to find the insertion point. This gives O(n) worst-case time.

Something like a skiplist could give O(log n) insertion. However, that's a different data structure to what you're asking about (and so are trees etc).

answered Apr 17, 2017 at 16:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.