I need to add unique integer elements from 2 singly linked lists to a 3rd list (meaning I have to add elements that are met once in their own list, not both).
Yet, I either get EXC_BAD_ACCESS error, no output or only one element is in the 3rd list.
Here is my structure of Node in singly linked list and function to add elements to a list.
struct Node {
int data;
Node* next;
};
void addNode(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
And function, that I use to add elements from one list to a list of unique elements:
void uniqueElements(Node* list1, Node* uniqueList) {
int count = 1;
for (Node *temp1=list1; temp1!=NULL; temp1=temp1->next){
for(Node *temp2=list1; temp2!=NULL; temp2=temp2->next){
if(temp1->data == temp2->data){
count++;
}
}
if(count == 1){
addNode(&uniqueList, temp1->data);
}
count = 1;
}
}
I fill the lists using for loop and addNode function, then I use uniqueElements function 2 times to fill the list of unique elements like this:
Node* listUnique = new Node;
uniqueElements(list1, listUnique);
uniqueElements(list2, listUnique);
I've tried lots of different methods, including using sets and maps, however they don't seem to fix the issue I have or add elements to a 3rd list. My only clue is that I reference to an empty list or null element of 3rd list.
I need to know how can I fix the code and output elements of 3rd list. How can I solve this problem?