Catalyst - 1 month ago 8

C Question

I need some ideas for a homework assignment that I have.

Consider the following definition:

`typedef struct listNode {`

int* dataPtr;

struct listNode* next;

} ListNode;

typedef struct list {

ListNode* head;

ListNode* tail;

} List;

Each list node represents a single digit.

Each number is represented by a list, but in a reversed manner: the last digit of the number is the first list-node of the list, and the first digit of the number is the last list-node of the list.

I've written the function

`void addNumbers(List n1, List n2, List *sum);`

which returns a new list with the sum of the other two lists.

Now I have to write the function for multiplication:

`void multNumbers(List n1, List n2 , List* prod);`

And I'm kinda stuck with how to implement it. It's not about the code, it's about how to do it.

Needless to say, we're not allowed to convert the numbers into an integer, multiply and go convert the result to a list.

Any help would be highly appreciated.

Thanks.

Answer

This will be a good exercise in code reuse. Since you already have created a function that adds two linked list numbers, can you utilize that function to perform (parts of) the multiplication? After all, multiplication can be performed by hand by repeatedly multiplying the first number by one of the digits from the second number, and then adding all of the results. Try something along these lines:

- Create a linked list number that will contain the result, and set it to zero
- Loop through the digits of the second number
- For each digit, multiply the first number by that digit (you should write a separate function that does this; if you managed to write the addition function, this shouldn't be too hard)
- Append zeroes to the end of the result so that the digits get shifted far enough to the left
- Add the number to the result, using
`addNumbers()`