✔ 最佳答案
#include <stdio.h>
#include <stdlib.h>
typedef struct N {
int coef;
int exp;
struct N* next;
} node;
node head_1 = { 0, -1, NULL};
node head_2 = { 0, -1, NULL};
node result = { 0, -1, NULL};
void enqueue( node* head, int c, int e )
{
node* ptr;
node* tmp;
ptr = (node *) malloc( sizeof( node));
ptr->coef = c;
ptr->exp = e;
ptr->next = NULL;
tmp = head;
while ( tmp->next != NULL ) {
tmp = tmp->next;
}
tmp->next = ptr;
}
void display( node* head )
{
node *ptr=head->next;
while ( ptr != NULL ) {
printf("%d, %d\n", ptr->coef, ptr->exp);
ptr = ptr->next;
}
}
void add( node* ptr1, node* ptr2, node* ptr3 )
{
node* tmp1=ptr1->next;
node* tmp2=ptr2->next;
while ( tmp1 != NULL && tmp2 != NULL ) {
enqueue( ptr3, tmp1->coef + tmp2->coef, tmp1->exp );
tmp1 = tmp1->next;
tmp2 = tmp2->next;
}
if ( tmp1 == NULL ) {
while ( tmp2 != NULL ) {
enqueue( ptr3, tmp2->coef, tmp2->exp );
tmp2 = tmp2->next;
}
} else if ( tmp2 == NULL ) {
while ( tmp1 != NULL ) {
enqueue( ptr3, tmp1->coef, tmp1->exp );
tmp1 = tmp1->next;
}
} else {
}
}
void clear_helper( node* ptr )
{
if ( ptr != NULL ) {
clear_helper( ptr->next );
free((void*) ptr );
}
}
void clear_q( node* ptr )
{
node* tmp=ptr;
clear_helper( tmp->next );
ptr->next = NULL;
ptr->coef = 0;
ptr->exp = -1;
}
int main()
{
enqueue( &head_1, 8, 0 );
enqueue( &head_1, 0, 1 );
enqueue( &head_1, 3, 2 );
enqueue( &head_1, 0, 3 );
enqueue( &head_1, 0, 4 );
enqueue( &head_1, 7, 5 );
display( &head_1 );
printf("\n");
enqueue( &head_2, 12, 0 );
enqueue( &head_2, 1, 1 );
enqueue( &head_2, 9, 2 );
enqueue( &head_2, 0, 3 );
enqueue( &head_2, 0, 4 );
enqueue( &head_2, 2, 5 );
enqueue( &head_2, 5, 6 );
display( &head_2 );
printf("\n");
add( &head_1, &head_2, &result );
display( &result );
clear_q( &result );
}