You need to look at the polynomial as a sequence of pairs (coefficient, variable):
[(coefficient1, variable1), (coefficient2, variable2), (coefficient3, variable3), ...]
As you described, you iterate over it from left to right, combining two adjacent pairs into one when the variable part is identical (this, of course, assumes that the list has already been sorted by the variable part!).
Now, what happens when there are three or more elements in this list that share their variables? Well then just keep combining them. There is actually no need for recursion or anything complicated.
At any time during the iteration, you combine the variable part of the current pair with the variable part for the last time you saw it . If they are identical, you combine them and just continue. If in the next pair you will have the same variable part as the last, then you will combine them again. If you do it right, there should be no duplicates.
Here is an example of how to do this. It works by creating a new list of pairs, and then iterating through the input list, for each element of the input list, it decides whether to combine it with the element last clicked on the new list, or by adding a new element to the new list
#include <utility> #include <vector> #include <iostream> typedef std::vector<std::pair<float,std::string>> Polynomial; Polynomial combine_like_terms(const Polynomial &poly) { if (poly.empty()) return poly; /* Here we store the new, cleaned-up polynomial: */ Polynomial clean_poly; /* Now we iterate: */ auto it = begin(poly); clean_poly.push_back(*it); ++it; while (it != end(poly)) { if (clean_poly.back().second == it->second) clean_poly.back().first += it->first; // Like term found! else clean_poly.push_back(*it); // Sequence of like-terms ended! ++it; } return clean_poly; } int main() { Polynomial polynomial { { 1.0 , "x^2" }, { 1.4 , "x^3" }, { 2.6 , "x^3" }, { 0.2 , "x^3" }, { 2.3 , "x" }, { 0.7 , "x" } }; Polynomial clean_polynomial = combine_like_terms(polynomial); for (auto term : clean_polynomial) std::cout << '(' << term.first << ',' << term.second << ")\n"; std::cout.flush(); return 0; }
You can easily make this a template again if you need to - I used float for coefficients and strings for the variable part. This is really just a code example to show how this can be done easily without recursion or many iterators used in parallel.
Oh, and the code is written for C ++ 11. Again, this is just a model and can be adjusted for C ++ 03.