C语言链表实现多项式加法 | 数据结构与算法
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int coefficient;
int exponent;
struct Node* next;
} Node;
Node* createNode(int coefficient, int exponent) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->coefficient = coefficient;
newNode->exponent = exponent;
newNode->next = NULL;
return newNode;
}
Node* buildPolynomial() {
Node* p = NULL;
while (1) {
int coefficient, exponent;
scanf('%d,%d', &coefficient, &exponent);
if (coefficient == 0 && exponent == 0) {
break;
}
Node* node = createNode(coefficient, exponent);
if (p == NULL) {
p = node;
} else {
Node* current = p;
while (current->next != NULL) {
current = current->next;
}
current->next = node;
}
}
return p;
}
Node* addPolynomials(Node* p1, Node* p2) {
Node* dummy = createNode(0, 0);
Node* current = dummy;
while (p1 != NULL && p2 != NULL) {
if (p1->exponent < p2->exponent) {
current->next = createNode(p1->coefficient, p1->exponent);
p1 = p1->next;
} else if (p1->exponent > p2->exponent) {
current->next = createNode(p2->coefficient, p2->exponent);
p2 = p2->next;
} else {
current->next = createNode(p1->coefficient + p2->coefficient, p1->exponent);
p1 = p1->next;
p2 = p2->next;
}
current = current->next;
}
if (p1 != NULL) {
current->next = p1;
}
if (p2 != NULL) {
current->next = p2;
}
return dummy->next;
}
void printPolynomial(Node* p) {
Node* current = p;
while (current != NULL) {
printf('%d,%d ', current->coefficient, current->exponent);
current = current->next;
}
printf('
');
}
int main() {
Node* polyA = buildPolynomial();
Node* polyB = buildPolynomial();
Node* result = addPolynomials(polyA, polyB);
printPolynomial(result);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/oID 著作权归作者所有。请勿转载和采集!