C语言学习笔记数据结构记录二
c语言数据结构线性表-链表----一元多项式相加
- 作业 :用链表创建两个一元多项式,并实现两个多项式相加
- 功能实现 尾插法创建单链表 两式相加 打印
#include<stdio.h>
#include<stdlib.h>
#define length sizeof(struct Polynode)
typedef struct Polynode
{
int coef;
int exp;
struct Polynode * next;
} Polynode, * PolyList;
void InitList(PolyList L)
{
(L) = (PolyList)malloc(sizeof(length));
(L) -> next = NULL;
}
PolyList creat_list(PolyList L)
{
Polynode *head,*rear,*s;
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;
return(head);
}
void PolyAdd(PolyList L1,PolyList L2)
{
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;
}
}
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;
p = p -> next;
}
}
else
{
printf("此为空表!\n");
}
}
int main()
{
void InitList(PolyList *L) ;
PolyList creat_list(PolyList L);
void PolyAdd(PolyList L1,PolyList L2);
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);
PolyAdd(L1,L2);
printf("\n相加之后...\n");
print_list(L1);
}