The concatenation of two lists is to be performed on time. Which of the following implementations of a list should be used?
View worked solution
Answer: C
To concatenate two lists and in time, we must be able to access the head and tail of both lists in time and update their connections.
In a Circular Doubly Linked List (CDLL), we only need a single pointer to the head of each list (say, head1 and head2):
- The tail of is directly accessible in time as
head1->prev. - The tail of is directly accessible in time as
head2->prev.
We can concatenate the two lists by updating a constant number of pointers:
- Identify the tails:
tail1 = head1->prevtail2 = head2->prev - Link the tail of the first list to the head of the second list:
tail1->next = head2head2->prev = tail1 - Link the tail of the second list back to the head of the first list to maintain circularity:
tail2->next = head1head1->prev = tail2
All these pointer manipulations take time.
Why other options are incorrect:
- Singly linked list / Doubly linked list: Without an explicit tail pointer, finding the tail node requires traversing the entire list, which takes time.
- Array implementation: Concatenating two arrays requires shifting elements or allocating a new larger array and copying elements, which takes time.
Free practice · Your answers on this page are not saved.
