#include <stdio.h> #include <stdlib.h> struct Node { int coefficient; // 系数 int exponent; // 指数。 struct Node *Next; }; typedef struct Node *PtrToNode; typedef PtrToNode Polynomial; void CreatList(PtrToNode *List) //创建链表 { PtrToNode r; PtrToNode s; int n; *List = (PtrToNode )malloc(sizeof(PtrToNode)); r = *List; printf("please input terms\n"); scanf("%d", &n); printf("please coefficients and exponents\n"); while (n--) { s = (PtrToNode)malloc(sizeof(PtrToNode)); scanf("%d", &s->coefficient); scanf("%d", &s->exponent); r->Next = s; r = s; } r->Next = NULL; } int exp1(int y, int x) // 指数函数的值 { int result = 1; while(x--) { result = result * y; } return result; } int ResultList(PtrToNode *List) // 链表的结果 { PtrToNode r; r = (*List)->Next; int result = 0; int y; printf("Please input value of y=\n"); scanf("%d", &y); while (r != NULL) { result += (r->coefficient)*exp1(y, r->exponent); r = r->Next; } return result; printf("\n"); } void PrintList(PtrToNode *List) //打印链表。 { PtrToNode r; r = (*List)->Next; while (r != NULL) { printf("%dy^%d", r->coefficient, r->exponent); if (r->Next != NULL) { printf(" + "); } r = r->Next; } printf("\n"); } int main(void) { PtrToNode List = NULL; CreatList(&List); //链表指针的地址。 PrintList(&List); printf("the result is %d\n", ResultList(&List)); return 0; }
我认为创建一元多项式并不难,关键在于怎么把链表的指针传进去。这需要涉及到指针参数传递的一些知识。下面附带个一个测试程序。把指针参数作为参数传给函数。
希望对大家都有所帮助。有什么需要探讨的。请留言。#include <stdio.h> #include <stdlib.h> void fn(int **p1) { int *p2 = (int *)malloc(sizeof(int)); *p2=10; *p1=p2; } void main() { // int *p = (int *)malloc(sizeof(int)); int *p; fn(&p); printf("d\n", *p); }
关于c 一元多项式链表的建立和打印
最新推荐文章于 2023-05-16 18:43:37 发布