I came upon an interesting question and I am puzzled with the answer provided to me. The question is as follows:
The concatenation of 2 lists can be performed O(1) time.
Which of the following implementation of list should be used?
- Singly Linked List
- Doubly Linked List
- Circular Linked List
- Array Implementation Of Linked List
I initially thought that a DLL would be the correct choice as concatenation can happen from both side, however the answer seems to CLL. I am confused. Any explanation will be most helpful. Thanks.
You can easily concatenate two lists in O(1) time using either a single linked list or a doubly linked list, provided that you have a pointer to the last node in at least one of the lists. (And, of course, pointers to the list heads.)
You can't do it with an array implementation, because you end up having to allocate more memory and copy the new resulting list to it. Even if the array already has memory allocated, you still have to copy all of the new items to it. So it's either O(m+n) or O(n) (where m and n are the lengths of the individual lists, respectively).
With a circularly linked list, you can easily concatenate them in O(1) time. It's just a matter of breaking a link in both lists, and then hooking them together. This assumes, of course, that the order of items isn't especially important.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With