用链表实现多项式相加
#include<iostream>
#include<cstdio>
#include<malloc.h>
#define flag -1
using namespace std;
typedef struct Node
{float coef;int expn;struct Node *next;
}LNode,*LinkList;void CreatLinkList(LinkList L)
{LNode *r,*s;float x;int y;scanf("%f%d",&x,&y);r=L;while(y!=0){s=(LinkList)malloc(sizeof(LNode));s->coef=x;s->expn=y;r->next=s;r=s;scanf("%f%d",&x,&y);}r->next=NULL;} LinkList Add_L(LinkList P,LinkList Q)
{LNode *p,*q;LNode *r,*s;float sum;p=P->next;q=Q->next;r=P;while(p&&q){if((p->expn)<(q->expn)){r->next=p;r=r->next;p=p->next;}else if((p->expn)>(q->expn)){r->next=q;r=r->next;q=q->next;}else {sum=(p->coef)+(q->coef);if(sum!=0){(p->coef)=sum;r->next=p;r=r->next;p=p->next;s=q;q=q->next;free(s); }else{s=p;p=p->next;free(s);s=q;q=q->next;free(s);} }}if(p)r->next=p;elser->next=q;free(Q);return P;
}void DisPlay(LinkList L)
{LinkList p=NULL;p=L->next;while(p!=NULL){printf("(%f,%d)",p->coef,p->expn);p=p->next;}cout<<endl;
}int main()
{LinkList L1,L2;L1=(LinkList)malloc(sizeof(LNode));L1->next=NULL;L2=(LinkList)malloc(sizeof(LNode));L2->next=NULL;cout<<"input L1"<<endl;cout<<"请输入L1的多个系数and指数,0 0结束"<<endl;cout<<"举个栗子:1^1+2^2+3^3输入为1 1 2 2 3 3 0 0回车"<<endl;CreatLinkList(L1);cout<<"input L2"<<endl;cout<<"请输入L1的多个系数and指数,0 0结束"<<endl;CreatLinkList(L2);LinkList t=Add_L(L1,L2);cout<<"相加后"<<endl;DisPlay(t);cout<<endl;}