70,021
社区成员




#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define MC (Count *)malloc(sizeof(struct Count));
struct Count
{
int Val;//系数
int Last;//指数
struct Count * pNext;
};
//造链表并赋值
struct Count * Make (void)
{
int val;
int last;
int len;//链表长度
int i;
struct Count * pHead = MC//头指针
if (pHead == NULL)
{
printf("分配内存失败!\n");
exit(-1);
}
struct Count * pList = MC//结点
pList = pHead;
pList->pNext = NULL;
printf("的项数为:");
scanf("%d",&len);
for (i=0;i<len;++i)
{
printf("第%d项为(系数,指数):",i+1);
scanf("%d,%d",&val,&last);
struct Count * pNew = MC
if (pHead == NULL)
{
printf("分配内存失败!\n");
exit(-1);
}
pNew->Val = val;
pNew->Last = last;
pList->pNext = pNew;
pNew->pNext = NULL;
pList = pNew;
}
return pHead;
}
//列出多项式
void List(Count * pHead)
{
struct Count * p = pHead->pNext;
while (p!=NULL)
{
printf("(%dX^%d)",p->Val,p->Last);
p = p->pNext;
if (p!=NULL)
putchar('+');
}
putchar('\n');
return;
}
//多项式相加处理
struct Count * Add (Count * pHead_1,Count * pHead_2)
{
pHead_1 = pHead_1->pNext;
while (pHead_1 != NULL)
{
pHead_1 =pHead_1->pNext;
if (pHead_1->pNext == NULL)
{
pHead_1->pNext = pHead_2;
break;
}
}
return pHead_1;
}
int main (void)
{
struct Count * phead_1 = NULL;
struct Count * phead_2 = NULL;
struct Count * phead_add = NULL;
printf("\n多项式<1>");
phead_1 = Make();
printf("\n你输入的多项式为:\n");
List(phead_1);
printf("\n多项式<2>");
phead_2 = Make();
printf("\n你输入的多项式为:\n");
List(phead_2);
phead_add = Add (phead_1,phead_2);
printf("\n多项式的和为:\n");
List(phead_add);
return 0;
}
/*
在VC++6.0运行结果是:
多项式<1>的项数为:2
第1项为(系数,指数):3,3
第2项为(系数,指数):4,2
你输入的多项式为:
(3X^3)+(4X^2)
多项式<2>的项数为:2
第1项为(系数,指数):2,4
第2项为(系数,指数):5,4
你输入的多项式为:
(2X^4)+(5X^4)
多项式的和为:
(-842150451X^-842150451)+(2X^4)+(5X^4)
Press any key to continue
*/