在C语言实现的一元多项式的相加操作中,怎样同时实现合并一个多项式中的同类项?

abcddd_1234 06:50:38
#include<stdio.h>
#include<malloc.h>
typedef struct Polynode

{
int coef;
int exp;
struct Polynode *next;
} Polynode;

Polynode* polycreate(/*Polynode *head*/)
{
Polynode *h, *rear, *s,*temp;
int c,e;
h=(Polynode *)malloc(sizeof(Polynode)); /*建立多项式的头结点*/
h->next = NULL;
scanf("%d%d",&c,&e);/*键入多项式的系数和指数项*/
while(c!=0) /*若c=0,则代表多项式的输入结束*/
{
s=(Polynode*)malloc(sizeof(Polynode)); /*申请新的结点*/
s->coef=c ;
s->exp=e ;
rear = h;//rear不再指向尾节点,而是从头结点开始遍历
temp = rear->next;
while(temp!=NULL && temp->exp <e)
{//循环到rear->exp<e,temp->exp>e,否则直到链表结尾
if(rear->exp==temp->exp) {rear->coef+temp->coef;}//此句为合并同类项
else{ rear = temp;
temp = rear->next;
}}
s->next = temp;//插入
rear->next = s;

scanf("%d%d",&c,&e);
}
return(h);
}

void polylist_add(Polynode *head1,Polynode *head2)
{
int sum;Polynode *temp;
Polynode *p=head1->next,*q=head2->next,*r=head1;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp) {r->next=p;r=r->next;p=p->next;}

else if(p->exp>q->exp) {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;temp=q;q=q->next;free(temp);}

else {temp=p->next;free(p);p=temp;

temp=q->next;free(q);q=temp;}
}
if(p!=NULL) r->next=p;
else
r->next=q;
}}

void printf_list(Polynode *head)
{
Polynode *p=head->next;
while(p)
{printf("%dx^%d",p->coef,p->exp);if(p->next)
printf("+");p=p->next;}
}

int main()
{
Polynode *head1,*head2;
//clrscr();
head1=polycreate(/*head1*/);
head2=polycreate(/*head2*/);
printf_list(head1);
printf("\n");
printf_list(head2);
printf("\n");
polylist_add(head1,head2);
printf_list(head1);
getchar();
getchar();
return 0;
}
为什么没有实现合并一个多项式中同类项的操作啊?
本人忒穷,没分啊,高手帮帮忙吧,谢谢啦!

Polynode* polycreate( /* Polynode *head */ ) {
Polynode *h, *rear, *s, *temp;
int c, e;
h = (Polynode*)malloc(sizeof(Polynode)); /* 建立多项式的头结点 */
h->next = NULL;
scanf("%d%d", &c, &e); /* 键入多项式的系数和指数项 */
while (c != 0) /* 若c=0,则代表多项式的输入结束 */ {
rear = h; // rear不再指向尾节点,而是从头结点开始遍历
temp = rear->next;
while (temp != NULL && temp->exp < e) {
rear = temp;
temp = rear->next;
}
if(temp!=NULL&&temp->exp==e)/*如果上面寻找退出时,temp不为空且它的指数和输入指数相同*/
{
temp->coef+=c;
}
else/*这是一个当前多项式没有出现的指数项,新建节点保存*/
{
s = (Polynode*)malloc(sizeof(Polynode)); /* 申请新的结点 */
s->coef = c;
s->exp = e;
s->next = rear->next; // 插入
rear->next = s;
}

scanf("%d%d", &c, &e);
}
return(h);
}

建议scanf("%d%d", &c, &e); 这里分成2句,如果c==0,直接退出录入
温馨提示:答案为网友推荐,仅供参考
相似回答