【每日刷题】 PAT 数据结构 02-线性结构2 一元多项式的乘法与加法运算 (20 分)

题目描述:
【每日刷题】 PAT 数据结构 02-线性结构2 一元多项式的乘法与加法运算 (20 分)_第1张图片
代码如下:

//一元多项式的乘法与加法运算
#include 
#include 

typedef struct dx{
	int a;
	int x;
	struct dx *next;
}D;

typedef D* P;

P read( );                     //读取
void print( P ptrd );          //输出
P add( P p1, P p2 );           //计算多项式相加 
void insert( P &L1, P &p );    //处理插入操作 
P mul( P p1, P p2 );           //计算多项式相乘
 
int main ( void )
{
	P p1, p2, p_add, p_mul;
	p1 = read();
	p2 = read();
	p_mul = mul( p1, p2 );
	print( p_mul ); 
	p_add = add( p1, p2 );
	print( p_add ); 
	return 0;
} 

P read( )
{
	int n;
	scanf( "%d", &n );
	P ptrd = ( P )malloc( sizeof( D ) );
	ptrd -> next = NULL;
	P p = ptrd;
	for( int i = 0; i < n; i++ ){
		int m, n;
		scanf( "%d%d", &m, &n );
		P s = ( P )malloc( sizeof( D ) );
		s -> a = m;
		s -> x = n;
		s -> next = NULL;
		p -> next = s;
		p = s;
	}
	return ptrd;
}

void print( P ptrd )
{
	if( ptrd -> next == NULL )
		printf( "0 0" );
	while( ptrd -> next != NULL ){
		if( ptrd -> next -> next == NULL )
			printf( "%d %d", ptrd -> next -> a, ptrd -> next -> x );
		else
			printf( "%d %d ", ptrd -> next -> a, ptrd -> next -> x );
		ptrd = ptrd -> next;
	}
	printf( "\n" );
}

P add( P p1, P p2 )
{
	P L1 = p1 -> next, L2 = p2 -> next;
	P p3 = ( P )malloc( sizeof( D ) );
	p3 -> next = NULL;
	P p = p3;
	while( L1 && L2 ){
		if( L1 -> x > L2 -> x )
			insert( L1, p );
		else if( L1 -> x < L2 -> x )
			insert( L2, p );
		else
			if( ( L1 -> a + L2 -> a ) != 0 ){
				P s = ( P )malloc( sizeof( D ) );
				s -> a = L1 -> a + L2 -> a;
				s -> x = L1 -> x;
				s -> next = NULL;
				p -> next = s;
				p = s;
				L1 = L1 -> next;
				L2 = L2 -> next;
			}
			else{
				L1 = L1 -> next;
				L2 = L2 -> next;
			}
	}
	if( L1 ) while( L1 ){ insert( L1, p ); }
	if( L2 ) while( L2 ){ insert( L2, p ); }
	return p3;
}

void insert( P &L1, P &p )
{
	P s = ( P )malloc( sizeof( D ) );
	s -> a = L1 -> a;
	s -> x = L1 -> x;
	s -> next = NULL;
	p -> next = s;
	p = s;
	L1 = L1 -> next;
}

P mul( P p1, P p2 )
{
	P L1 = p1 -> next, L2 = p2 -> next;
	P p3 = ( P )malloc( sizeof( D ) );
	p3 -> next = NULL;
	while( L1 ){
		P temp = ( P )malloc( sizeof( D ) );
		temp -> next = NULL;
		P t = L2, t1 = temp;
		while( t ){
			P s = ( P )malloc( sizeof( D ) );
			s -> a = ( L1 -> a ) * ( t -> a );
			s -> x = ( L1 -> x ) + ( t -> x );
			s -> next = NULL;
			t1 -> next = s;
			t1 = s;
			t = t -> next;
		}
		p3 = add( temp, p3 );
		L1 = L1 -> next;
	}
	return p3;
}

这道题整整想了两天的空闲时间,一个小时写完,感觉对链表的使用更加熟悉了,继续加油。

你可能感兴趣的:(数据结构MOOC——PAT习题)