In: Computer Science
Below is for C language
typedef struct _node {
Node *next;
char *str;
} Node;
You are given a function that takes in two Node* pointers to two different linked lists. Each linked list node has a string represented by a character array that is properly null terminated. You're function is supposed to return true if the concatenation of strings in a linked list match each other, else return false.
EXAMPLES
List 1: "h" -> "el" -> "l" -> "o" -> NULL
List 2: "he" -> "llo" -> NULL
Return: True
List 1: "je" -> "lc -> "l" -> "o" -> NULL
List 2: "h" -> "e" -> "ll" -> "" -> "o" -> NULL
Return: False
List 1: “e” -> “llo” -> “h” -> NULL
List 2: “h” -> “e” -> “l” -> “l” -> “o” -> NULL
Return: False
bool areListsMatching(Node *list1, Node *list2) {
// TODO: Fill this
}
Here is the solution to above problem in C. Please read the code comments for more information
PLEASE GIVE A THUMBS UP!!!
Explanation
1) Traverse the list1 and concatenate string from all the nodes in a single string using strcat function from string.h
2) Do the same as step 1 for the list2
3) Compare both the concatenated strings using strcmp function from string.h if return value is zero which means both are same return true else false
C Code
bool areListsMatching(Node *list1, Node *list2) {
//find the concated string for first string
Node * cur1= list1;
char first[100]="";
while(cur1!=NULL)
{
//concatenate and create the first
string
strcat(first,cur1->str);
cur1=cur1->next;
}
//find the concated string for second string
Node * cur2= list2;
char second[100]="";
while(cur2!=NULL)
{
//concatenate and create the second
string
strcat(second,cur2->str);
cur2=cur2->next;
}
//compare both string if equal return true else
false
if(strcmp(first,second)==0)
return true; //same
return false; //not same
}