您的位置:首页 > 其它

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

2010-06-16 21:32 369 查看
/*
* 一元多项式加法,利用单链表实现
*/
#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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: