# c语言数据结构线性表-链表----一元多项式相加

## c语言数据结构线性表-链表----一元多项式相加

• 作业 ：用链表创建两个一元多项式,并实现两个多项式相加
• 功能实现 尾插法创建单链表 两式相加 打印
#include<stdio.h>
#include<stdlib.h>
#define length sizeof(struct Polynode)

//定义节点结构
typedef struct Polynode
{
int coef;
int exp;
struct Polynode * next;  /*建立next指针*/
} Polynode, * PolyList;

// 初始化
void InitList(PolyList L)   /*注意PolyList结构指针类型*/
{
(L) = (PolyList)malloc(sizeof(length));     /* L相当于链表头指针变量  */
(L) -> next = NULL;
}

//尾插法
PolyList creat_list(PolyList L)
{
int coef,exp;
rear = L;  //建立尾节点
printf("请输入系数和指数\n");
scanf("%d,%d",&coef,&exp);  //输入数据
while(coef != 0)
{
s = (PolyList)malloc(sizeof(Polynode));  //申请新节点
s -> coef = coef;
s -> exp = exp;
rear -> next = s; //上一个尾节点指向新插入的节点
rear = s;   //新插入节点位置给尾节点
printf("请输入系数和指数\n");
scanf("%d,%d",&coef,&exp);  //输入数据
}
rear -> next = NULL;
}

//相加
{
Polynode *p,*q,*tail,*temp;
int sum;
p = L1 -> next;
q = L2 -> next;
tail = L1;

while(p!=NULL && q!=NULL)
{
if(p -> exp < q -> exp)
{
tail -> next = p;
tail = p;
p = p -> next;
}
else if (p -> exp == q -> exp)
{
sum = p -> coef + q -> coef;
if (sum != 0)
{
p -> coef = sum;
tail -> next = p;
tail = p;
p = p -> next;
temp = q;
free(temp);
q = q -> next;
}
else
{
temp = p ; p = p -> next; free(temp);
temp = q ; q = q -> next; free(temp);
}
}

else
{

tail -> next = q;
tail = p;
q = q -> next;
}

if (p!= NULL) tail -> next = p;
else tail -> next = q;
}
// return(tail);
}

//打印
void print_list(PolyList L)
{
Polynode *p;
if (L -> next != NULL)
{
p = L -> next;  //定义首节点
printf("F(x) = ");
while(p != NULL)
{

printf("%dX^%d",p -> coef,p -> exp);
if (p ->next != NULL) printf("+");
else break;  //因为是以输出0结尾的  所以尾节点不要输出
p = p -> next;
}

}
else
{
printf("此为空表！\n");
}
}

int main()
{
void InitList(PolyList *L) ;
PolyList creat_list(PolyList L);
void print_list(PolyList L);
Polynode A,B;
PolyList L1,L2;
L1 = &A;L2 = &B;
printf("\n方程一...\n");
creat_list(L1);
print_list(L1);
printf("\n方程二...\n");
creat_list(L2);
print_list(L2);
printf("\n相加之后...\n");
print_list(L1);
}


05-03

01-18
02-05 3万+
03-16 3346
03-22 2598
04-07 7191
12-07 6305
04-20 1万+
04-12
09-21 6709
12-25
10-28 2万+