您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)C語言中如何實(shí)現(xiàn)多項(xiàng)式的相加,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
具體內(nèi)容如下
包含帶頭節(jié)點(diǎn)的鏈表的初始化,輸出:
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>typedef struct Pol{ int coe; // 系數(shù) int index; // 指數(shù) struct Pol *next;}Pol; int main(int argc, char *argv[]){ Pol *head1 = NULL; // 第一個(gè)多項(xiàng)式 Pol *head2 = NULL; // 第二個(gè)多項(xiàng)式 Pol *Initiate(Pol *head1); // 聲明初始化函數(shù) void Output(Pol *head); // 聲明輸出函數(shù) void PolAdd(Pol *head1, Pol *head2); // 聲明相加函數(shù) int coe, index; char sign; Pol *p; int n = 0; // 初始化第一個(gè)多項(xiàng)式 head1 = Initiate(head1); p = head1; while (1) { scanf("%dx%d%c", &coe, &index, &sign); p->next = (Pol *)malloc(sizeof(Pol)); p = p->next; p->coe = coe; p->index = index; p->next = NULL; if(sign == '\n') break; } printf("第一多項(xiàng)式輸入完畢。\n"); // 初始化第二個(gè)多項(xiàng)式 head2 = Initiate(head2); p = head2; while (1) { scanf("%dx%d%c", &coe, &index, &sign); p->next = (Pol *)malloc(sizeof(Pol)); p = p->next; p->coe = coe; p->index = index; p->next = NULL; if (sign == '\n') break; } printf("第二多項(xiàng)式輸入完畢。\n"); // 調(diào)用相加函數(shù)和輸出函數(shù) PolAdd(head1, head2); Output(head1); system("PAUSE"); return 0;}// 初始化鏈表函數(shù)Pol *Initiate(Pol *head){ head = (Pol *)malloc(sizeof(Pol)); head->next = NULL; return head;}// 初始化相加函數(shù)void PolAdd(Pol *head1, Pol *head2){ Pol *p = head1->next; Pol *q = head2->next; Pol *pre = head1; Pol *temp = NULL; int sum; while ((p != NULL) && (q != NULL)) { if (p->index < q->index) { pre->next = p; pre = pre->next; p = p->next; } else if(p->index == q->index) { sum = p->coe + q->coe; if (sum != 0) { p->coe = sum; pre->next = p; pre = pre->next; p = p->next; // 刪除節(jié)點(diǎn) temp = q; q = q->next; free(temp); } else { temp = p; p = p->next; free(temp); temp = q; q = q->next; free(temp); } } else { pre->next = q; pre = pre->next; q = q->next; } } // 兩串長(zhǎng)度不相等時(shí),把尾部一次加入 if (p != NULL) pre->next = p; else pre->next = q; }// 輸出函數(shù)void Output(Pol *head){ Pol *p = head; p = p->next; int i = 0; while (p) { if (p->coe > 0 && i != 0) { printf("+%dX^%d", p->coe, p->index); p = p->next; } else { printf("%dX^%d", p->coe, p->index); p = p->next; } i++; }}
關(guān)于C語言中如何實(shí)現(xiàn)多項(xiàng)式的相加就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。