首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言實現多項式相加:鏈表儲存與合併演算法

     編輯:關於C語言
 

多項式相加程式碼 (C語言)

適合初學者參考,採用鏈表儲存多項式節點 (係數、指數、下一節點),實現建立、相加、列印功能。

核心結構與常數

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define LEN sizeof(node)

typedef struct polynode {
    int coef;              // 係數
    int exp;               // 指數
    struct polynode *next; // 下一項
} node;

建立多項式鏈表

node *create(void) {
    node *h, *r, *s;
    int c, e;
    h = (node *)malloc(LEN); r = h;
    printf("coef:"); scanf("%d", &c);
    printf("exp: "); scanf("%d", &e);
    while (c != 0) {
        s = (node *)malloc(LEN);
        s->coef = c; s->exp = e;
        r->next = s; r = s;
        printf("coef:"); scanf("%d", &c);
        printf("exp: "); scanf("%d", &e);
    }
    r->next = NULL;
    return h;
}

輸入係數為 0 結束。帶表頭節點,h 為表頭,r 尾指標。

多項式相加演算法

void polyadd(node *polya, node *polyb) {
    node *p, *q, *pre, *temp;
    int sum;
    p = polya->next; q = polyb->next; pre = polya;
    while (p != NULL && q != NULL) {
        if (p->exp < q->exp) {           // A 指數較小,接入結果
            pre->next = p; pre = p; p = p->next;
        } else if (p->exp == q->exp) {   // 指數相同,係數相加
            sum = p->coef + q->coef;
            if (sum != 0) {
                p->coef = sum;
                pre->next = p; pre = p;
                p = p->next; temp = q; q = q->next; free(temp);
            } else {                     // 係數抵銷,刪除兩節點
                temp = p->next; free(p); p = temp;
                temp = q->next; free(q); q = temp;
            }
        } else {                         // B 指數較小,接入結果
            pre->next = q; pre = q; q = q->next;
        }
    }
    if (p != NULL) pre->next = p;
    else pre->next = q;
}

就地修改 polya 為結果,釋放多餘節點。

列印與主程式

void print(node *p) {
    while (p->next != NULL) {
        p = p->next;
        printf("  %d*x^%d", p->coef, p->exp);
    }
}

int main() {
    node *polya, *polyb;
    printf("Welcome!\n");
    printf("Input polya (coef exp):\n"); polya = create(); print(polya);
    printf("\nInput polyb (coef exp):\n"); polyb = create(); print(polyb);
    printf("\nSum:\n"); polyadd(polya, polyb); print(polya);
    return 0;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved