I am sorry to bother, but i really need some help.Having been struggling for hours. Here is some code i wrote for my assignment. My assignment is to implement a template function called merge which used to merged two double linkedlist into a new list.
But it turned to "SIGSEGV - Segmentation violation signal" when testing my code in a case below:
TEST_CASE("Testing merge: Left and right lists non-empty; same size", "[weight=1]") {
LinkedList<int> left;
left.pushBack(1);
left.pushBack(5);
left.pushBack(10);
left.pushBack(20);
LinkedList<int> right;
right.pushBack(2);
right.pushBack(4);
right.pushBack(11);
right.pushBack(19);
LinkedList<int> expectedList;
expectedList.pushBack(1);
expectedList.pushBack(2);
expectedList.pushBack(4);
expectedList.pushBack(5);
expectedList.pushBack(10);
expectedList.pushBack(11);
expectedList.pushBack(19);
expectedList.pushBack(20);
auto studentResultList = left.merge(right);
SECTION("Checking that values are correct") {
REQUIRE(studentResultList == expectedList);
}
SECTION("Checking that the list prev links and tail pointer are being set correctly") {
REQUIRE(studentResultList.assertPrevLinks());
}
SECTION("Checking that the list size is being tracked correctly") {
REQUIRE(studentResultList.assertCorrectSize());
}
}
//I can't figure out what is wrong.Below is my code:
//this is a member function
template <typename T>
LinkedList<T> LinkedList<T>::merge(const LinkedList<T>& other) const {
LinkedList<T> left = *this;
LinkedList<T> right = other;
LinkedList<T> merged;
Node* temp = merged.head_;
Node* temp1 = left.head_;
Node* temp2 = right.head_;
//check if one of the list is empty.
if(!left.head_){
merged = right;
return merged;
}
if(!right.head_){
merged = left;
return merged;
}
//determine the first node for the new merged list
if(temp1->data >= temp2->data){
temp->data = temp2->data;
temp2 = temp2->next;
}
else{
temp->data = temp1->data;
temp1 = temp1->next;
}
//loop until the end of one list
while(temp1 && temp2){
if(temp1->data >= temp2->data){
temp->next->data = temp2->data;
temp2 = temp2->next;
}
else{
temp->next->data = temp1->data;
temp1 = temp1->next;
}
temp = temp->next;
}
//loop over the not empty list
while(!temp1 && temp2){
temp->next->data = temp2->data;
temp2 = temp2->next;
temp = temp->next;
}
while(!temp2 && temp1){
temp->next->data = temp1->data;
temp1 = temp1->next;
temp = temp->next;
}
return merged;
}