解释下 a=(PolyList)malloc(sizeof(Node));
时间: 2023-04-10 14:04:53 浏览: 76
这是一个动态内存分配的语句,它将分配一个大小为 Node 结构体的内存块,并将其强制转换为 PolyList 类型的指针,然后将其赋值给变量 a。这样做的目的是为了在程序运行时动态地分配内存,以便存储数据结构中的节点信息。
相关问题
while(a!=NULL){ PolyList s;s=(PolyList)malloc(sizeof(Node)); s->coef=a->coef;s->exp=a->exp; c->next=s;s->next=NULL; c=c->next;a=a->next; } while(b!=NULL){ PolyList s;s=(PolyList)malloc(sizeof(Node)); s->coef=(-1)*b->coef;s->exp=b->exp; c->next=s;s->next=NULL; c=c->next;b=b->next; }
这段代码是用来实现多项式的加法运算的。其中a和b分别表示两个多项式的头结点,c表示结果多项式的头结点。代码中使用了while循环来遍历两个多项式,并将它们的系数和指数分别赋值给新的节点s,然后将s插入到结果多项式c的末尾。其中第二个while循环中的系数取相反数是为了实现减法运算。
C语言 用链表结构存储多项式,求两个多项式A加B的和 要求在建立多项式链表时,总是按照指数从大到小排列的 代码
#include <stdio.h>
#include <stdlib.h>
/* 多项式结构体 */
typedef struct node {
float coef; /* 系数 */
int expn; /* 指数 */
struct node *next;
}PolyNode, *PolyList;
/* 创建多项式链表 */
void CreatePolyList(PolyList *L) {
int n, i;
float c;
int e;
PolyNode *p, *q;
printf("请输入多项式项数:");
scanf("%d", &n);
*L = (PolyNode *)malloc(sizeof(PolyNode));
(*L)->next = NULL;
q = *L;
printf("请输入多项式每一项的系数和指数:\n");
for (i = 1; i <= n; i++) {
p = (PolyNode *)malloc(sizeof(PolyNode));
scanf("%f %d", &c, &e);
p->coef = c;
p->expn = e;
/* 按指数从大到小插入 */
while(q->next && q->next->expn < e) {
q = q->next;
}
p->next = q->next;
q->next = p;
q = *L; /* 重置q指针 */
}
}
/* 两个多项式相加 */
void AddPolyList(PolyList A, PolyList B, PolyList *C) {
PolyNode *pa, *pb, *pc, *p;
pa = A->next;
pb = B->next;
*C = (PolyNode *)malloc(sizeof(PolyNode));
(*C)->next = NULL;
pc = *C;
while (pa && pb) {
if (pa->expn > pb->expn) {
p = (PolyNode *)malloc(sizeof(PolyNode));
p->coef = pa->coef;
p->expn = pa->expn;
pc->next = p;
pc = pc->next;
pa = pa->next;
}
else if (pa->expn < pb->expn) {
p = (PolyNode *)malloc(sizeof(PolyNode));
p->coef = pb->coef;
p->expn = pb->expn;
pc->next = p;
pc = pc->next;
pb = pb->next;
}
else {
/* 指数相同,系数相加 */
p = (PolyNode *)malloc(sizeof(PolyNode));
p->coef = pa->coef + pb->coef;
p->expn = pa->expn;
pc->next = p;
pc = pc->next;
pa = pa->next;
pb = pb->next;
}
}
/* 处理剩余项 */
while (pa) {
p = (PolyNode *)malloc(sizeof(PolyNode));
p->coef = pa->coef;
p->expn = pa->expn;
pc->next = p;
pc = pc->next;
pa = pa->next;
}
while (pb) {
p = (PolyNode *)malloc(sizeof(PolyNode));
p->coef = pb->coef;
p->expn = pb->expn;
pc->next = p;
pc = pc->next;
pb = pb->next;
}
pc->next = NULL;
}
/* 输出多项式链表 */
void PrintPolyList(PolyList L) {
PolyNode *p = L->next;
while (p) {
printf("%.2fx^%d", p->coef, p->expn);
p = p->next;
if (p) {
printf(" + ");
}
}
printf("\n");
}
int main() {
PolyList A, B, C;
printf("请输入多项式A:\n");
CreatePolyList(&A);
printf("请输入多项式B:\n");
CreatePolyList(&B);
printf("多项式A:");
PrintPolyList(A);
printf("多项式B:");
PrintPolyList(B);
AddPolyList(A, B, &C);
printf("A + B = ");
PrintPolyList(C);
return 0;
}
阅读全文