读书人

帮朋友问一个c语言的编程?该如何解决

发布时间: 2012-03-01 10:25:46 作者: rapoo

帮朋友问一个c语言的编程?
用一个链表示一个n次多项式,每一个结点的数据部分包括指数和系数(用指数将它们连起来)编写一个程序实现两个一元n次多项式相加,合并时,指数相同,系数相加;指数不同,链表插入.



[解决办法]
#include <stdio.h>
#include <malloc.h>
#define NULL 0

struct DataNode
{
float coefficient; //系数
int exponent_one; //x的指数
int exponent_two; //y的指数
struct DataNode *next; //指针
};

typedef DataNode DataTerm; //DataTerm即每一项数据,为结构体类型

/***********链表的创建为最基本问题,不多说***********/
DataTerm *Input(void)
{
DataTerm *Head,*p, *q;
int n = 0; //用来记录结点的个数,编程的习惯,可以记录也可以不用
p = q = (struct DataNode *)malloc(sizeof(struct DataNode)); //强制性转换开辟的空间
scanf( "%f,%d,%d\n ",&p-> coefficient,&p-> exponent_one,&p-> exponent_two);
Head = p;
if(p-> coefficient == 0)
return NULL;
while(p-> coefficient != 0)
{
n = n+1;
if(n == 1)
{
Head = p;
}
else
{
q-> next = p;
q = p;
p = (struct DataNode *)malloc(sizeof(struct DataNode));
scanf( "%f,%d,%d\n ",&p-> coefficient,&p-> exponent_one,&p-> exponent_two);
}
}
q-> next = NULL;
return Head;
}

/***********题意知算法根据x指数降序进行结点排序**********/
DataTerm *Add(DataTerm *Head_one,DataTerm *Head_two)
{
DataTerm *p, *q, *r,*p_end; //r指向链表A中p结点的前一个结点指针
p = Head_one; //链表A的头指针赋值给p
q = Head_two; //链表B的头指针赋值给q
if(Head_one == NULL && Head_two == NULL)
return NULL;
if(Head_one != NULL && Head_two == NULL)
return Head_one;
if(Head_one == NULL && Head_two != NULL)
return Head_two;
if(Head_one != NULL && Head_two != NULL)
{
while(p-> next != NULL)
{
p = p-> next;
}
p_end = p;
while(q != NULL)
{
p = Head_one;
while(p != NULL)
{
if((q-> exponent_one == p-> exponent_one)&&(q-> exponent_two
== p-> exponent_two))
{
p-> coefficient = p-> coefficient + q-> coefficient;
if(q = Head_two)
{
r = q;
if(q-> next != NULL)
{

Head_two = q-> next;
q = Head_two;
free(r);
}
else
{
free(r);
Head_two = NULL;
}
}
else
{
if(q-> next-> next == NULL)
{
r = q-> next;
q = r;
q-> next = NULL;
free(r);
}
if(q-> next == NULL)
{
q = NULL;
}
else
{
r = q-> next;
q = r;
q-> next = q-> next-> next;
free(r);
}
}
}
else
{
r = q;
p_end-> next = r;
r = p_end;
p_end-> next = NULL;
Head_two = q-> next;
q = Head_two;
}
p = p-> next;
}
}
}

return Head_one;
}
仅供参考,只有思路

读书人网 >C语言

热点推荐