List Product
Difficulty: ⚫◯◯◯
Tags: linked-list, traversal, math
Hurdle: Passing this question is sufficient to pass the linked lists hurdle.
Description
Write a function product that is given two arguments, head1 and head2, which are pointers to the first nodes of two linked lists.
The function should return the sum of the products of corresponding elements from both lists:
- Multiply the 1st element of list1 with the 1st element of list2
- Multiply the 2nd element of list1 with the 2nd element of list2
- And so on...
- Sum all these products together
Important: If one list is longer than the other, the extra elements should be ignored.
Examples
Example 1
List 1: 3 -> 1 -> 4 -> 1 -> 5 -> 9 -> X
List 2: 2 -> 7 -> 9 -> X
Output: 49
Explanation: 3×2 + 1×7 + 4×9 = 6 + 7 + 36 = 49. The extra elements (1, 5, 9) in list1 are ignored.
Example 2
List 1: 2 -> 7 -> X
List 2: 4 -> 42 -> 4242 -> 4242 -> X
Output: 302
Explanation: 2×4 + 7×42 = 8 + 294 = 302. The extra elements in list2 are ignored.
Example 3
List 1: 2 -> 4 -> 6 -> X
List 2: 42 -> X
Output: 84
Explanation: Only 2×42 = 84 (only one pair of corresponding elements).
Example 4
List 1: (empty)
List 2: 1 -> 2 -> 3 -> 4 -> X
Output: 0
Explanation: No corresponding elements, so the result is 0.
Example 5
List 1: 4 -> 3 -> 2 -> 1 -> X
List 2: (empty)
Output: 0
Explanation: No corresponding elements, so the result is 0.
Function Signature
int product(struct node *head1, struct node *head2);
Data Structure
struct node {
struct node *next;
int data;
};
Constraints
- The lists may be different lengths.
- The
datafields may contain any integer (positive, negative, or zero). productshould return only a single integer.- Do not change the linked lists provided.
- Do not change the
nextordatafields of list nodes. - Do not use arrays.
- Do not call
malloc. - Do not call
scanf,getchar, orfgets. - Do not call
printf(the function should only return a value).
Hints
- Traverse both lists simultaneously.
- Stop when either list reaches NULL.
- Initialize your sum to 0.
Testing
The command line uses - to separate the two lists.
./list-product 3 1 4 1 5 9 - 2 7 9 8
57
./list-product 16 7 8 12 - 13 19 21 12
653
./list-product 2 4 6 - 42
84
./list-product - 1 2 3 4
0
./list-product 4 3 2 1 -
0
./list-product -
0