#include <iostream>
#include <iomanip>
using namespace std;
 
struct wiel {
    int coeff;
    int pow_val;
    wiel* nowy;
};
 
class dodaj {
    wiel *wiel1, *wiel2, *wiel3;
 
public:
    dodaj() { wiel1 = wiel2 = wiel3 = NULL; }
    void dodaj_wiel();
    void wyswietl();
};
 
void dodaj::dodaj_wiel()
{
    int i, p;
    wiel *nowy1 = NULL, *koniec = NULL;
    cout << "Wpisz x :\n"; cin >> p;
    //Pierwszy Wielomian
    cout << "\nPierwszy Wielomian\n"; for (i = p; i >= 0; i--) {
        nowy1 = new wiel;
        nowy1->pow_val = p;
        cout << "Wprowadź Współczynnik dla stopnia " << i << ": "; cin >> nowy1->coeff;
        nowy1->nowy = NULL;
        if (wiel1 == NULL)
            wiel1 = nowy1;
        else
            koniec->nowy = nowy1;
        koniec = nowy1;
    }
 
    //Drugi Wielomian
    cout << "\n\nDrugi Wielomian\n"; koniec = NULL; for (i = p; i >= 0; i--) {
        nowy1 = new wiel;
        nowy1->pow_val = p;
        cout << "Wprowadź Współczynnik dla stopnia " << i << ": "; cin >> nowy1->coeff;
        nowy1->nowy = NULL;
        if (wiel2 == NULL)
            wiel2 = nowy1;
        else
            koniec->nowy = nowy1;
        koniec = nowy1;
    }
 
    //Addition Logic
    wiel *p1 = wiel1, *p2 = wiel2;
    koniec = NULL;
    while (p1 != NULL && p2 != NULL) {
        if (p1->pow_val == p2->pow_val) {
            nowy1 = new wiel;
            nowy1->pow_val = p--;
            nowy1->coeff = p1->coeff + p2->coeff;
            nowy1->nowy = NULL;
            if (wiel3 == NULL)
                wiel3 = nowy1;
            else
                koniec->nowy = nowy1;
            koniec = nowy1;
        }
        p1 = p1->nowy;
        p2 = p2->nowy;
    }
}
 
void dodaj::wyswietl()
{
    wiel* t = wiel3;
    cout << "\n\nWyprowadź wynik : ";
    while (t != NULL) {
        cout.setf(ios::showpos);
        cout << t->coeff;
        cout.unsetf(ios::showpos);
        cout << "X" << t->pow_val;
        t = t->nowy;
    }
}
int main()
{
    dodaj obj;
    obj.dodaj_wiel();
    obj.wyswietl();
}


