Linked List Concatenation In O(1) Time

五迷三道 提交于 2019-12-03 15:14:15

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!