您的位置:首页 > 编程语言 > C语言/C++

多项式加法(单链表 c语言)

2014-03-31 20:29 387 查看
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct pnode
{
float coef;
int expn;
struct pnode *next;
} pnode;

pnode * creat()
{
float input_coef;
int input_expn;
pnode *head=NULL;
pnode *prev, *current;
while(scanf("%f%d",&input_coef,&input_expn)&&(input_expn>=0))
{
current=(pnode *)malloc(sizeof(pnode));
if(head==NULL)
head=current;
else
prev->next=current;
current->next=NULL    ;
current->coef=input_coef;
current->expn=input_expn;
prev=current;
//    printf("input coef,expn:\n");
}
return head;
}

void display(pnode *head)
{
pnode *current;
current=head;
while(current!=NULL)
{
printf("%.1f  %d\n",current->coef,current->expn);
current=current->next;
}
printf("\n");
}

pnode * add(pnode *heada,pnode *headb)
{
pnode *headc=NULL;
pnode *p=heada,*q=headb;
pnode *current,*prev;

while(p!=NULL&&q!=NULL)
{
current=(pnode *)malloc(sizeof(pnode));
if(headc==NULL)
headc=current;
else
prev->next=current;
current->next=NULL ;
if(p->expn==q->expn )
{
//printf("%d\n",p->expn);
if(p->coef+q->coef!=0)
{
current->coef=p->coef+q->coef;
current->expn=p->expn;
prev=current;
}
q=q->next;
p=p->next;
}
else if(p->expn>q->expn)
{
//printf("%d  %d\n",p->expn,q->expn);
current->coef=p->coef;
current->expn=p->expn;
prev=current;
p=p->next;
}
else
{
//printf("%d  %d\n",p->expn,q->expn);
current->coef=q->coef;
current->expn=q->expn;
prev=current;
q=q->next;
}
}
while(p!=NULL)
{
current=(pnode *)malloc(sizeof(pnode));
if(headc==NULL)
headc=current;
else
prev->next=current;
current->next=NULL;
current->coef=p->coef;
current->expn=p->expn;
prev=current;
p=p->next;
}
while(q!=NULL)
{
current=(pnode *)malloc(sizeof(pnode));
if(headc==NULL)
headc=current;
else
prev->next=current;
current->next=NULL;
current->coef=q->coef;
current->expn=q->expn;
prev=current;
q=q->next;
}
return headc;
}

void BubbleSort(pnode *head)
{
pnode *i=NULL,*j=NULL;
int temp_expn;
float temp_coef;
for(i = head; i!= NULL; i = i -> next)
for(j=i->next; j!=NULL; j=j->next)
if(i->expn<j->expn)
{
temp_expn=j->expn;
temp_coef=j->coef;
j->coef=i->coef;
j->expn=i->expn;
i->expn=temp_expn;
i->coef=temp_coef;
}
}

int Delete(pnode *head)
{
pnode *temp;
while(head!=NULL)
{
temp=head->next;
free(head);
head=temp;
}
if(head==NULL)
return 1;
}

int main()

{
freopen("input.txt","r",stdin);
pnode * a,*b,*c;
printf("input the first:\n");
a=creat();
BubbleSort(a);
printf("input the second:\n");
b=creat();
BubbleSort(b);
c=add(a,b);
printf("the first:\n");
display(a);
printf("the second:\n");
display(b);
printf("sum is:\n");
display(c);
Delete(a);
Delete(b);
Delete(c);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: