Reputation: 13
What is the asymptotic complexity of the addLast(), or add(), or offer() equivalent methods in java.util.LinkedList? Is it O(N) or O(1)? That is, does the LinkedList keep a pointer to its tail internally, or does it traverse the list from the head?
Either way, how would you make use of a FIFO Queue concrete implementation that's more efficient at the offer() method but still uses standard libraries? (no custom queue implementation). Is LinkedList a good choice or something else?
I realize this question was probably asked before, but I can't find an answer after searching quite a while.
Upvotes: 1
Views: 3782
Reputation: 393781
Yes, the list keeps a pointer to the tail, as you can read in the class JavaDoc.
All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
Therefore operations like addLast()
and add()
take O(1) time.
The documentation specifically says LinkedList is suitable for a queue implementation.
Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue.
Upvotes: 6
Reputation: 1451
addLast()
O(1), Java just needs to make a new node and point its previous node value to the now second to last node, and then point that nodes next node value to the newly created node.
add()
If you specify an index, O(N) (N/2 really since it'll traverse from either the front or back depending on the index you specified). If you don't specify an index, O(1) since it's essentially the same as addLast()
Upvotes: 3