- #include
- using namespace std;
- typedef struct node
- {
- float coef;//系数
- int expn;//指数
- struct node* next;
- }list, * linklist;
- void Createlist(linklist& l)
- {
- l = new list;
- l->next = NULL;
- linklist p, q;
- q = l;
- cout << "输入多项式项数:" << endl;
- int n;
- cin >> n;
- for (int i = 0; i < n; i++)
- {
- p = new list;
- cout << "分别输入指数,系数:" << endl;
- cin >> p->expn >> p->coef;
- q->next = p;
- q = p;
- }
- q->next = NULL;
- }
- void Mpsort(linklist& L)//链表冒泡排序
- {
- linklist p = L->next,q;
- for (p = L->next; p != NULL; p = p->next)
- {
- for (q = p->next; q != NULL; q = q->next)
- {
- list tmp;
- if (p->expn > q->expn)
- {
- tmp.coef = p->coef;
- p->coef = q->coef;
- q->coef = tmp.coef;
- tmp.expn = p->expn;
- p->expn = q->expn;
- q->expn = tmp.expn;
- }
- }
- }
- }
- void Add(linklist& L1, linklist& L2)
- {
- linklist p1, p2, p3, r;
- r = NULL;
- p1 = L1->next, p2 = L2->next;
- p3 = L1;//新加多项式用L1表头
- while (p1 && p2)//两链表都不为空
- {
- if (p1->expn == p2->expn)//指数相等,进行运算
- {
- int sum = p1->coef + p2->coef;
- if (sum != 0)//系数和不为0
- {
- p1->coef = sum;//和存入链表一
- p3->next = p1;//新链表指向p1
- p3 = p1;
- p1 = p1->next;//p1往下走
- r = p2;
- p2 = p2->next;//p2往下走
- delete r;
- }
- else//和为0
- {
- r = p1; p1 = p1->next; delete r;//p1往下走
- r = p2; p2 = p2->next; delete r;//p2往下走
- }
- }
- else if (p1->expn < p2->expn)//p1中的指数小于p2中的指数
- {
- p3->next = p1;//新链表指向p1
- p3 = p1;
- p1 = p1->next;
- }
- else//p2中的指数小于p1中的指数
- {
- p3->next = p2;//新链表指向p2
- p3 = p2;
- p2 = p2->next;
- }
- }
- p3->next = p1 ? p1 : p2;//p1不为空,接p1;p1为空,接p2
- delete L2;
- }
- void Printlist(linklist& l)
- {
- linklist p;
- p = l->next;
- cout << "f = ";
- while (p->next!=NULL)
- {
- if (p->expn == 0)
- cout << p->coef<<" + ";
- else
- cout << p->coef << "x^" << p->expn << " + ";
- p = p->next;
- }
- cout << p->coef << "x^" << p->expn ;
- cout << endl;
- }
- int main()
- {
- linklist L1, L2;
- Createlist(L1);
- Mpsort(L1);
- Createlist(L2);
- Mpsort(L2);
- cout << "多项式一:" << endl;
- Printlist(L1);
- cout << "多项式二:" << endl;
- Printlist(L2);
- Add(L1, L2);
- cout << "多项式相加:" << endl;
- Printlist(L1);
- }