c语言一元多项式求和

一元多项式求和

比较拉跨基本实现功能,没多少注释 链表头指针不存数据合并同类项要手动 相加是比较拉跨的算法第二个链表与第一个链表中的一个循环比较,最后排序还拉跨算法也许有bug仅作参考

#include <stdio.h>
#include <stdlib.h> 

struct List{
	int coe;//系数 
	int exp;//项 
	struct List *next;
};

void ListSort(struct List *head1)
{
	struct List *p,*q;	
	int temp1,temp2;
	p = head1;
	p = p->next;
	while(p){
		q = p->next;
		while(q){
			if(p->exp > q->exp){
				temp1 = p->exp;
				p->exp = q->exp;
				q->exp = temp1;
				temp2 = p->coe;
				p->coe = q->coe;
				q->coe = temp1;
			}
			q = q->next;		
		}
		p = p->next;
	}
    
 } 

void ListDelete(struct List *p,struct List *q,int i) 
{
	struct List *s;
	if((p->exp == i)&&(((q->next)->exp)==i)){
		s = q->next ;
		q->next = s->next;
		free(s);
	}

}

void ListJoin(struct List *head1,struct List *head2) 
{
	struct List *p,*q,*s;
	p = head1;
	q = head2;
	while(p->next){
		p = p->next;
	}
	if(q->next){
		s = q->next;
		p->next = s;
		free(s);		
	}
}

int Listadd(struct List *head,int i,int data1,int data2)
{
	struct List *p,*s;
	int j = 0;
	p = head;
	while(p && j<i-1){
		p = p->next;
		j++;
	}
	if(!p||j>i-1)
	return 0;
	s = (struct List*)malloc(sizeof(List));
	s->coe = data1;
	s->exp = data2;
	s->next = p->next;
	p->next = s;
	return 1;	
}

struct List* ListCreat (void)
{
	int data1,data2,i,num,status=0;
	struct List *head,*s;
	s = (struct List*)malloc(sizeof(List));
	s -> next = NULL;
	head = s;
	printf("输入一元多项式多少项;");
	scanf("%d",&num);
	for(i=0;i<num;i++){
		printf("\n输入系数项数:");
		scanf("%d%d",&data1,&data2);
		status += Listadd(s,i+1,data1,data2);
	}
	if(status == num){
		printf("CreatSuccess\n");
    }else{
    	printf("CreatFail\n");
	}
	return head;	
}

void ListDisplay(struct List *head)
{
	struct List *p;
	p = head;
	p = p->next;
	while(p){		
		printf("%dX^%d+",p->coe,p->exp);
		p = p->next;
	}
	printf("\b \n");
}
 
struct List* ListAnd(struct List* head1,struct List* head2) //相加 
{
	struct List *p,*q,*s,*b;
	int dataq1=0,dataq2=0,datap1=0,datap2=0;
	p = head1;
	q = head2;
	while(p->next){
  		p = p->next;		
		datap2 = p->exp;
		while(q->next){
			b = q;
			q = q->next;
			dataq2 = q->exp;
			if(dataq2 == datap2){
			p->coe += q->coe ;
			ListDelete(p,b,dataq2);//删除已经求和的 
			q = head2;
			break;
			} 
		} 
	}
	ListJoin(head1,head2);//有多余的项相加
	ListSort(head1);//排序
	return head1;
} 
 
int main (void)
{
	struct List* head1;
	struct List* head2;
	struct List* head3;
	head1 = ListCreat ();
	head2 = ListCreat ();
	ListDisplay(head1);
	ListDisplay(head2);
	head3 = ListAnd(head1,head2); 
	ListDisplay(head3);
	return 0;
}

后面运行效果在这里插入图片描述
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值