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.
Answer is Circular doubly linked List
For merging of list you have to point next pointer of last node of 1st list to first node of 2nd list. To do this in O(1) time circular doubly linked list is useful. You can go to last node of 1st list by head1->next->previous. And modify this field pointing to head2->next. And also modify head2->next->previous to head1->next.
If in sinlgy and doubly linked list pointer to last node of any one list is given then you can do the merging of two list in O(1).
There seem to be multiple correct answers.
You can concatenate two singly-linked lists in O(1) time as long as you store pointers to both the first and last elements of the list. You'd just rewire the next pointer of the last element of the first list to the first element of the second list. This also works with doubly-linked lists.
You can also concatenate two circularly-linked lists in O(1) time by using a similar trick.
The only option that doesn't work is the array-based list.
Hope this helps!
You don't need a last, but you do need a next
Assume the each list has at least two elements
void merge( node* first, node* second )
{
node * first_next = first->next;
node * second_next = second->next;
first->next = second_next;
second->next = first_next;
}
As Jim Mischel has said, any list will work just fine.
These two:
- Doubly Linked List
- Circular Linked List
are correct answers. Both support O(1) concatenation.
来源:https://stackoverflow.com/questions/25938499/linked-list-concatenation-in-o1-time