利用 線性表 數據結構 求一元多項式的和數據結構
附代碼(插入操做 當表長超過初始長度時 元素賦值會有問題 記下來 之後研究)
app
#include <stdio.h> #include <stdlib.h> #define ERROR 0 #define OK 1 #define INIT_SIZE 5 #define INCERMENT 5 typedef int ElemType; typedef struct { ElemType *elem; int length; int size; }List; int InitList(List *L) { //apply memory for list //integer poniert L->elem = (ElemType *) malloc(INIT_SIZE * sizeof(ElemType)); if (!L->elem) { return ERROR; } L->length = 0; L->size = INIT_SIZE; return OK; } //插入元素須要作哪些操做(越界的那一次操做沒有給元素附上值) int InsertElem(List *L, int i, ElemType e) { //邊界判斷 if ( i<1 || i > L->length+1 ) { return ERROR; } ElemType *new; //whether it needs to apply memory for new element if ( L->length > L->size ) { new = (ElemType*) realloc(L->elem, (L->length + INCERMENT) * sizeof(ElemType)); if ( !new ) { return ERROR; } L->elem = new; L->length += INCERMENT; } //把i之後的元素向後移動 高位向低位移動 ElemType *p = &L->elem[i - 1]; //第i個的位置 ElemType *q = &L->elem[L->length - 1]; //最後一個元素的位置 //逐個日後退一 for (; q >= p; q--) { *(q + 1) = *q; } *p = e; ++L->length; return OK; } int findElemByIndex(List L, int i, ElemType *e) { if ( i<0 || i>L.length ) { return ERROR; } *e = L.elem[i-1]; return OK; } int main() { //initilize a linear_table List L; if ( InitList(&L) ) { printf("InitList successful\n"); ElemType e; //tips printf("Please enter the length of arr\n"); int num; scanf("%d",&num); int arr[num],i=0; printf("Please each element:\n"); for (;i < num; i++) { scanf("%d", &arr[i]); InsertElem(&L, i+1, arr[i]); } int sum = 0; i = 0; for (;i < num; i++) { printf("i:%d\n", i); printf("e:%d\n", L.elem[i]); sum += L.elem[i]; } printf("\nsum:%d\n", sum); //計算一元多項式的和 //思路 把每一項的值存入一個節點 遍歷節點相加 求和 } }