Search code examples
algorithmlinked-listqueue

Queue implemented by linked list with O(n) time complexity


As the title says, I want to implement a queue using a linked list. However, when I try to implement enqueue or dequeue, I have to traverse the linked list to get the last element, which has a time complexity of O(n). On the other hand, using an array to implement the queue can achieve O(1) time complexity. Is there any approach that allows me to implement these operations with O(1) time complexity, perhaps by using another pointer or something similar?

Can I get the last element with a time complexity of O(1) in a linked list?

Looking forward to your answer!


Solution

  • Consider a doubly linked list using a single node as a sentinel node, which does not store data but points to the head and the tail of your list, making the list circular. By maintaining a reference to the sentinel node, your enqueue function can add new elements directly after the tail, and your dequeue function can remove elements directly from the head. This is a neat implementation where the sentinel node simplifies the boundary conditions, and allows for constant time for both operations.