資料結構問題程式設計

2009-05-06 3:22 am
使用C語言的鏈結結構儲存二個多項式,以建立副程式執行多項式相加的運算,最後將結果輸出。例如:A(X)=7X5+3X2+8,B(X)=5X6+2X5+9X2+X+12。輸出:C(X)=5X6+9X5+12X2+X+20

回答 (1)

2009-05-06 2:45 pm
✔ 最佳答案
#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 );
}




收錄日期: 2021-05-01 23:54:39
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090505000016KK07403

檢視 Wayback Machine 備份