一元多项式加法——单链表实现

/*

 * 一元多项式加法,利用单链表实现

 */

#include "stdio.h"

#include "malloc.h"

#include "conio.h"


typedef struct ListNode

{

int factor;             /*多项式系数*/

    struct ListNode *next;  /*指向下一个节点的指针*/

} ListNode,*List;


List InitList()

{

ListNode *head,*rear,*s;

int f;

head = (ListNode *)malloc(sizeof(ListNode));  /*建立多项式的头节点*/

rear = head; 

printf("Please input factor:");

 

scanf("%d",&f);

while(f!=-1)   /*输入-1作为结束符*/

{

s = (List)malloc(sizeof(List));

s->factor=f;

rear->next=s;

rear=s;

printf("Input  next  factor:");

scanf("%d",&f);

}

rear->next=NULL;

return head;

}


void PloyAdd(List LA,List LB)

{

int i;

ListNode *head,*temp;

head=LA;

temp=head->next;

/*多项式相加*/

    getch();

while(LA!=NULL&&LB!=NULL)

{

LA->factor=LA->factor+LB->factor;

if(LA->next==NULL&&LB->next!=NULL)

{

LA->next=LB->next;

break;

}

LA=LA->next;

LB=LB->next;

}

/*输出运算结果*/

i=0;

printf("/nThe result is:/n");

while(temp!=NULL)

{

if(!i)

printf("%d",temp->factor);

else

printf("%dX^%d",temp->factor,i);

if(temp->next!=NULL)

printf("+");

temp=temp->next;

i++;

}

free(temp);

printf("/nWell done! /n/n");

}


void main()

{

List InitList();

void PloyAdd(List LA,List LB);


List ListA,ListB;


printf("Please input ListA/n");

ListA=InitList();

printf("/nPlease input ListB/n");

ListB=InitList();


    PloyAdd(ListA,ListB);


free(ListA);

free(ListB);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值