国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設(shè)計 > 正文

單向鏈表 練習3.6 多項式相加

2019-11-06 06:31:15
字體:
供稿:網(wǎng)友

3.6  編寫將兩個多項式相加的函數(shù)。不要毀壞輸入數(shù)據(jù)。用一個鏈表實現(xiàn)。

我的想法是   先將兩個多項式按照exponent(次方)進行排序,相同次方的進行合并,再將這兩個多項式進行相加。

多項式的結(jié)構(gòu)體定義如下:

struct Node{	int coefficient;	int exponent;	Position next;};

具體函數(shù)實現(xiàn)方法如下:

首先是排序算法:

/* 冒泡排序多項式,按照項的次數(shù)從小到大排序 */void MPSort( Position h , int size ){	Position p;	for( int i = 0; i < size-1; i++ )	{		p = h->next;		while( p != NULL && p->next != NULL )		{			if ( p->exponent > p->next->exponent )			{				Swap2Position( h, p, p->next );  //交換兩個結(jié)點			}			else if ( p->exponent == p->next->exponent )			{				Union2Position( p, p->next );   //合并兩個結(jié)點			}			else			{				p = p->next;   //指針移到下一個結(jié)點			}		}	}	return;} /* 交換兩個相鄰的結(jié)點 */void Swap2Position( Position h, Position p1, Position p2 ){	Position p0;	p0 = FindPRevious( h, p1 );	p1->next = p2->next;	p2->next = p1;	p0->next = p2;	return;} /* 合并兩個次數(shù)相同的結(jié)點 */void Union2Position( Position p1, Position p2 ){	if ( p1->exponent == p2->exponent )	{		p1->coefficient = p1->coefficient + p2->coefficient;		p1->next = p2->next; 		free( p2 );	}}接著是多項式相加的算法 (按照次數(shù)升序排序的)

/* 將兩個以排好序(升序)的多項式相加 */Position Add2Polynomial( Position h1, Position h2 ){	int size;	Position h;	Position p1, p2;	p1 = h1->next;	p2 = h2->next;	h = ( Position )malloc(sizeof(struct Node));	h->next = NULL;	while ( p1 != NULL && p2 != NULL )	{		if ( p1->exponent < p2->exponent )		{			InsertPolynomial( h, p1->coefficient, p1->exponent );  //將p1指向的結(jié)點插入到新的多項式中			p1 = p1->next;			size++;		}		else if ( p1->exponent > p2->exponent )		{			InsertPolynomial( h, p2->coefficient, p2->exponent );  //將p2指向的結(jié)點插入到新的多項式中			p2 = p2->next;			size++;		}		else		{			InsertPolynomial( h, p1->coefficient + p2->coefficient, p1->exponent );   //將兩個結(jié)點的系數(shù)相加 然后插入到新的多項式中			p1 = p1->next;			p2 = p2->next;			size++;		}	}	while ( p1 != NULL )	{		InsertPolynomial( h, p1->coefficient, p1->exponent );		p1 = p1->next;		size++;	}	while ( p2 != NULL )	{		InsertPolynomial( h, p2->coefficient, p2->exponent );		p2 = p2->next;		size++;	}	//排序	MPSort( h, size ); 	return h;}

中間的插入算法:

void InsertPolynomial( Position h, int coefficient, int exponent ){	Position tmpCell;	tmpCell = ( Position )malloc(sizeof(struct Node));	tmpCell->coefficient = coefficient;	tmpCell->exponent = exponent;	tmpCell->next = h->next;	h->next = tmpCell;} 


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 洪洞县| 大同县| 临西县| 勐海县| 林周县| 阿荣旗| 洪泽县| 深圳市| 石渠县| 雷山县| 宜州市| 咸宁市| 江源县| 托里县| 新邵县| 三河市| 曲靖市| 巴林左旗| 玛沁县| 巧家县| 江都市| 鸡西市| 色达县| 大关县| 泾川县| 吉林省| 香河县| 天津市| 建昌县| 旌德县| 瑞昌市| 霞浦县| 宣城市| 鄂伦春自治旗| 井陉县| 景泰县| 永兴县| 台南县| 柘荣县| 新化县| 蒲城县|