输入的时候按指数按顺序从大到小输入
输入系数为0 输入结束
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define OK 1
#define ERROR 0
#include<string.h>
/*1.多项式存储,系数、指数、指针域
2. 建表
3.数学比较,指数相同系数相加,系数为0不加入新链表,系数不为0,加入新链表,指数不同比较大小放入新链表
*/
struct Node{
int coef;
int exp;
struct Node *next;
};
Node* Init(Node* &L)
{ /*创建链表或初始化时一定要为头结点申请空间!*/
L=(Node*)malloc(sizeof(Node));
L->next=NULL;
return L;
}
Node* Create(Node* &L)
{ int c,e;
Node *r,*s;
L=(Node*)malloc(sizeof(Node));
L->next=NULL;
r=L;
scanf("%d%d",&c,&e);
while(c!=0)
{
s=(Node*)malloc(sizeof(Node));
s->coef=c;
s->exp=e;
r->next=s;
r=s;
scanf("%d%d",&c,&e);
}
r->next=NULL;
return L;
}
Node* Insert(Node* &L,int c,int e)
{ Node *r,*s;
if(L->next==NULL)
{r=L;
}
s=(Node*)malloc(sizeof(Node));
s->coef=c;
s->exp=e;
r->next=s;
r=s;
r->next=NULL;
return L;
}
Node* Add(Node* &L1,Node* &L2,Node* &L3)
{
Node *p=L1->next,*q=L2->next;
int nc;
while(p!=NULL&&q!=NULL)
{
if(p->exp>q->exp)
{
L3=Insert(L3,p->coef,p->exp);
p=p->next;
}
else if(p->exp<q->exp)
{
L3=Insert(L3,q->coef,q->exp);
q=q->next;
}
else if(p->exp==q->exp)
{
nc=p->coef+q->coef;
if(nc!=0)
{
L3=Insert(L3,nc,p->exp);
}
p=p->next;
q=q->next;
}
}
while(p!=NULL)
{
L3=Insert(L3,p->coef,p->exp);
p=p->next;
}
while(q!=NULL)
{
L3=Insert(L3,q->coef,q->exp);
q=q->next;
}
return L3;
}
void Show(Node* &L)
{
Node* p=L->next;
while(p!=NULL)
{
printf("%d~%d ",p->coef,p->exp);
p=p->next;
}
printf("\n");
}
int main()
{
Node *L1,*L2,*L3;
L1=Create(L1);
Show(L1);
L2=Create(L2);
Show(L2);
L3=Init(L3);
L3=Add(L1,L2,L3);
Show(L3);
}