This is my code:
#include <iostream>
using namespace std;
typedef struct Node
{
int data;
Node* next;
}Node;
class LinkedList
{
private:
Node* first;
Node* last;
public:
LinkedList() {first = last = NULL;};
LinkedList(int A[], int num);
~LinkedList();
void Display();
void Concatenate(LinkedList b);
};
// Create Linked List using Array
LinkedList::LinkedList(int A[], int n)
{
Node* t = new Node;
t->data = A[0];
t->next = NULL;
first = last = t;
for (int i = 1; i < n; i++)
{
t = new Node;
t->data = A[i];
t->next = NULL;
last->next = t;
last = t;
}
}
// Deleting all Node in Linked List
LinkedList::~LinkedList()
{
Node* p = first;
Node* tmp;
while (p != NULL)
{
tmp = p;
p = p->next;
delete tmp;
}
}
// Displaying Linked List
void LinkedList::Display()
{
Node* tmp;
for (tmp = first; tmp != NULL; tmp = tmp->next)
cout << tmp->data << " ";
cout << endl;
}
// Concatenate two linked list
void LinkedList::Concatenate(LinkedList b)
{
// We can use last pointer which point to last Node of first linked list
// Make it to point to the first Node of second linked list
last->next = b.first;
b.first = NULL;
}
int main()
{
int arr1[] = {4, 8, 12, 14, 18};
int arr2[] = {2, 6, 10, 16};
LinkedList l1(arr1, 5);
LinkedList l2(arr2, 4);
l1.Display();
l2.Display();
// Concatenate first linked list with second linked list
l1.Concatenate(l2);
l1.Display();
return 0;
}
I try to learn how to Concatenate two Linked List. And the result is correct. Which connect arr1
and arr2
in main()
function.
But, what I don't understand is there's a warning on my Compiler said:
free(): double free detected in tcache 2
When I try to check using Valgrind, there's so much Error inside Heap which makes me not understand more. But it seems like it's not Free all the Nodes properly.
Is there something wrong in my code? What should I change to make the warning disappear? Perhaps there's another way to Concatenate Linked List? And maybe someone can explain me what double free means. Thank You.