//一元多项式加减计算器
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int coef;
int expen;
struct node *next;
}List;
int Compare_Polyn( int a, int b )
{
if( a > b ){
return 1;
}
if( a = b ){
return 0;
}
if( a < b ){
return -1;
}
}
List *Create_Polyn( List* current, int a, int b )
{
List *p = (List *)malloc(sizeof(List));
p->coef = a;
p->expen = b;
if( current != NULL ){
current->next = p;
current = current->next;
current->next = NULL;
return current;
}
else{
printf("ERROR: the current pointer is NULL!\n");
return current;
}
}
void Add_Polyn( List * p1, List *p2 , List * head3 )
{
if( p1==NULL || p2==NULL ){
printf("ERROR: Add_Polyn is wrong!\n");
}
List *p3;
p3 = head3;
while( p1 && p2 ){
switch( Compare_Polyn( p1->expen, p2->expen ) ){
case 1 :
Create_Polyn( p3, p2->coef, p2->expen ); p2++; break;
case 0 :
Create_Polyn( p3, (p1->coef + p2->coef), ( p1->expen ) ); p1++; p2++; break;
case -1 :
Create_Polyn( p3, p1->coef, p1->expen);p1++; break;
default :
printf("ERROR: switch and compare is wrong!\n"); break;
}
}
while( p1 ){
p3 = Create_Polyn( p3, p1->coef, p1->expen );
p1++;
}
while( p2 ){
p3 = Create_Polyn( p3, p2->coef, p2->expen );
p2++;
}
}
void Print_Polyn( List * head3 )
{
while( head3 != NULL ){
printf("%d %d\n", head3->coef, head3->expen );
}
}
int main()
{
int a, b;
List * head1, *p1;
head1 = (List *)malloc( sizeof( List) );
p1 = head1;
p1->next = NULL;
printf("请按照规范输入第一个一元多项式(以系数和指数都为0时结束):\n");
scanf("%d %d", &a, &b);
//生成存放第一个一元多项式的链表
while( b ){
p1 = Create_Polyn( p1, a, b );
scanf("%d %d", &a, &b);
}
p1->next = NULL;
p1 = head1->next;
int c, d;
List * head2, *p2;
head2 = (List *)malloc( sizeof( List) );
p2 = head2;
printf("请按照规范输入第二个一元多项式(以系数和指数都为0时结束):\n");
scanf("%d %d", &c, &d);
//生成存放第二个一元多项式的链表
while( d ){
p2 = Create_Polyn( p2, c, d );
scanf("%d %d", &c, &d);
}
p2->next = NULL;
p2 = head2->next;
//第三个链表用来存放结果
List *head3;
head3 = (List *)malloc( sizeof( List) );
head3->next = NULL;
Add_Polyn( p1, p2, head3);
//开始打印
Print_Polyn( head3 );
return 0;
}
刚学数据结构不久,还望各位帮帮我这只小菜鸡。
可以提供截图看看吗?