I have read your code.
You have memory issues inside the function addPolyomials.
This problem is caused bad a wrong logic: Leeor has given you the solution in his answer yet: you need to add the words else
before the 2nd and 3rd if
s.
If you don't, then the when the 1st if gives TRUE, a new pointer is created and added to the list, and an advance is done.
Thus, when tne 2nd if
is reached, the comparisson is done with these new advanced pointers.
This is a logical error.
By doing this change to the program, there are some issues yet.
Since you initialize polynomial3 to garbage, this is shown in the final result.
Maybe you have to initialize, also, the components exp and coef (to 0?).
polynomial3->exp = 0;
polyoomial3->coef = 0;
You have an error in main()
when you "create" polynomial2.
There, you are using the list polynomial1.
The line has to be changed to:
polynomial2 = addTerm(polynomial2,exp,coef);
With theses changes, we can watch the logic itself of the program.
I obtained a nonsense solution.
I think that your idea of defining some "pending" flag is not enough.
Your logic seems to consider the polynomials as if they were the exponents in order.
But the user will not enter the polynomials in this way.
Your examples at the top of your question have the exponents unordered (the first polynomial).
I think it could be good idea to handle your lists at the moment they are entered, putting the terms in order. Since the terms are added one at the time, this can be easily achieved by searching in the list from the top of it, and inserting the terms properly.
For example, if you have 5x^2 + 6x^3 + 9
, the first step would insert 5 2 at the top of the list polynomial1. In the next iteration the pair 6 3 will inserted again at the top, before the pair (5, 2), and so on. Your final list would be:
(6, 3, next), (5, 2, next), (9, 0, next), NULL
This procedure ensures that you can iterate as you want.
(There is a minor problem: what happens if the user enters a repeated exponent? In this case no new element is added to the list: just add the new coefficient!)
Finally, we can analyze the "pending" coefficientes issue in the sum.
Observe that your while()
is iterating only if both lists are not NULL.
When the while()
arrives to its end, only three situations are possible:
(polynomial1 != NULL && polynomial2==NULL)
or well (polynomial2 != NULL && polynomial1==NULL),
or well both are NULL.
It is enough to check for (polynomial1 != NULL) and (polynomial2 != NULL).
In the 1st case, just "paste" the pending terms of polynomial1 to polynomial3.
In the 2nd case, do the same for polynomial2.
Finally, in the display function you could handle in a better way the terms with coefficient 0.
Probably it is better that the terms with coefficient 0 be not shown.
Your program needs much more improvement, but this is out of the scope of your question.