数据结构-一元多项式加法

7-17 一元多项式的加法 (20 分)

设计程序求两个一元多项式的和。

输入格式:

输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数。数字间以空格分隔。

输出格式:

输出1行,以指数递降方式输出和多项式非零项的系数和指数(保证不超过整数的表示范围)。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。

输入样例:

4 3 4 -5 2  6 1  -2 0
3 5 20  -7 4  3 1

输出样例:

5 20 -4 4 -5 2 9 1 -2 0
#include 
#include 
#include
typedef struct Node* list;
struct Node  
{
    int c;
    int e;
    list next;
};
int n;
list Read()
{
	list head,rear,s; 
	int c, e; 
	head = (list)malloc(sizeof(struct Node)); 
	rear = head;
		for(int i = 0; i < n; i ++)
		{
			scanf("%d %d",&c,&e);
       		s = (list)malloc(sizeof(struct Node));
        	s->c = c;
        	s->e = e;
            rear->next = s;
        	rear = s;
     } 
    
    rear->next = NULL;
    return head;
}
void Print( list p )
{
	 list a = p->next ;
	int flag = 0; 
	while(a&& a->c) 
	{ 
		if(flag)
			printf(" %d %d",a->c,a->e); 
		else
		{
			printf("%d %d",a->c,a->e); 
			flag = 1;
		}	
		a = a->next; 
	} 
	if(!flag)
		printf("0 0");
}
list Add( list a, list b ){
  list c = (list)malloc(sizeof(struct Node));
  c->next = NULL;
  list tail = c;
  list pa,pb;
  pa = a->next;
  pb = b->next;
  while(pa!=NULL&&pb!=NULL){
    if(pa->e > pb->e){
      list newnode = (list)malloc(sizeof(struct Node));
      newnode->c = pa->c;
      newnode->e = pa->e;
      newnode->next = NULL;
      tail->next = newnode;
      tail = newnode;
      pa = pa->next;
    }
    else if(pa->e < pb->e){
      list newnode = (list)malloc(sizeof(struct Node));
      newnode->c = pb->c;
      newnode->e = pb->e;
      newnode->next = NULL;
      tail->next = newnode;
      tail = newnode;
      pb = pb->next;
    }
    else{
      if((pa->c + pb->c)!=0){
        list newnode = (list)malloc(sizeof(struct Node));
        newnode->c = pa->c + pb->c;
        newnode->e = pa->e;
        newnode->next = NULL;
        tail->next = newnode;
        tail = newnode;
      }
      pa = pa->next;
      pb = pb->next;
    }
  }
  
  if(pb==NULL){
    while(pa!=NULL){
      list newnode = (list)malloc(sizeof(struct Node));
      newnode->c = pa->c;
      newnode->e = pa->e;
      newnode->next = NULL;
      tail->next = newnode;
      tail = newnode;
      pa = pa->next;
    }
  }
  else{
    while(pb!=NULL){
      list newnode = (list)malloc(sizeof(struct Node));
      newnode->c = pb->c;
      newnode->e = pb->e;
      newnode->next = NULL;
      tail->next = newnode;
      tail = newnode;
      pb = pb->next;
    } 
  }
  return c;
}
int main()
{
    list a, b, s;
    scanf("%d",&n);
  	a = Read();
    scanf("%d",&n);
	b = Read();
    s = Add(a, b);
    Print(s);
    return 0;
}

 

你可能感兴趣的:(数据结构-一元多项式加法)