c语言用链表的方式实现多项式加减,如何实现C语言单链表多项式相加的操作

#include#pragma warning(disable:4996)//兼容scanf

typedef struct node {

int coef;

int expon;

struct node* link;

}Polynode,*Polynomial;

Polynomial InsertPolyLinklist(Polynomial in,Polynomial Pread) {

Pread->link = in;

Pread = in;

in->link = NULL;

return Pread;

}

Polynomial ReadPoly(void) {

Polynomial Pread = (Polynomial)malloc(sizeof(Polynode));

Pread->link = NULL;

Polynomial H = Pread;

int N;

scanf("%d ", &N);

while (N--) {

Polynomial p = (Polynomial)malloc(sizeof(Polynode));

scanf("%d %d", &p->coef, &p->expon);

Pread= InsertPolyLinklist(p,Pread);

}

Polynomial F;

F = H->link;

free(H);

return F;

}

void PrintPoly(Polynomial F) {

while(F != NULL) {

printf("%d %d ", F->coef, F->expon);

F = F->link;

}

printf("\n");

}

Polynomial Add(Polynomial p1, Polynomial p2) {

Polynomial t1=p1,t2=p2;

Polynomial p=(Polynomial)malloc(sizeof(Polynode));

p->link = NULL;

Polynomial q = p;

Polynomial read;

while (t1&&t2) {

if (t1->expon == t2->expon) {

if (t1->coef + t2->coef) {

t1->coef = t1->coef + t2->coef;

t1->expon = t1->expon;

read = t1;

q->link = read;

q = read;

t1 = t1->link;

t2 = t2->link;

}

}

else {

if (t1->expon > t2->expon){

read = t1;

q->link = read;

q = read;

t1 = t1->link;

}

else {

if (t1->expon expon) {

read = t2;

q->link = read;

q = read;

t2 = t2->link;

}

}

}

}

if (t1) {

q->link = t1;

}

if (t2) {

q->link = t2;

}

Polynomial F = p->link;

free(p);

return F;

}

int main(void) {

Polynomial p1, p2, pp, ps;

p1 = ReadPoly();

PrintPoly(p1);

p2 = ReadPoly();

PrintPoly(p2);

pp = Add(p1, p2);

PrintPoly(pp);

// ps = Mult(p1, p2);

// PrintPoly(ps);

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值