Muidul Alam 2hin
Muidul Alam 2hin

Reputation: 189

Concatenatee two Lists in c++ in O(1) Complexity

We can concatenate two Linked List in O(1) time if we know the last element. So, Is there any way to concatenate two List in C++ using built-in data structures or I have to implement linked list myself then use it?

Upvotes: 4

Views: 6969

Answers (2)

Vashdev Heerani
Vashdev Heerani

Reputation: 679

Try this code this will merge two lists

list<int> list1 = { 5,9,0,1,3,4 };
list<int> list2 = { 8,7,2,6,4 }; 
list1.merge(list2);

Upvotes: -3

Sebastian Redl
Sebastian Redl

Reputation: 72044

std::list<int> l1 = create();
std::list<int> l2 = create();
l1.splice(l1.end(), l2);

Note that this empties l2 and moves its elements to l1.

Upvotes: 14

Related Questions