gpt4 book ai didi

c - 多项式的链表表示

转载 作者:行者123 更新时间:2023-11-30 20:43:27 26 4
gpt4 key购买 nike

我必须编写一个程序来对两个多项式求和。为此,首先,我正在编写一个程序来获取两个多项式并打印它们。

我的程序是这样的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node
{
int power;
int coef;
struct node *link;
};



int input( struct node *Phead);
int display( struct node *Phead);

int main()
{
struct node *Phead= malloc(sizeof(struct node)),*Qhead = malloc(sizeof(struct node));
input(Phead);
display(Phead);

input(Qhead);
display(Qhead);

return 0;
}

int input( struct node *Phead)
{
//Phead
//Qhead = malloc(sizeof(struct node));
int value;

printf("\n\t\tEntry of polynomial:\n");

printf("Enter the coefficient: ");
scanf("%d",&Phead->coef);
printf("Enter the power: ");
scanf("%d",&Phead->power);
Phead->link = NULL ;

printf("Enter the coefficient,( 0 to break ): ");
scanf("%d", &value);

while ( value != 0 )
{
struct node *new_node = malloc(sizeof(struct node ));

new_node -> coef = value;

printf("Enter the power: ");
scanf("%d",&new_node->power);
new_node->link = Phead;
Phead = new_node;
//printf("%d",Phead->power);
printf("Enter the coefficient,( 0 to break ): ");
scanf("%d", &value);
}
return 0;
}

int display( struct node *Phead)
{
struct node *temp = Phead;
//printf("I am in display.\n");

while ( temp != NULL )
{
//printf("I am in while.\n");
printf("%d * x ^ %d + ",temp->coef,temp->power);
temp=temp->link;
}
//printf("%d * x ^ %d + ",temp->coef,temp->power);
//printf("0");

return 0;
}

我无法打印多项式。问题出在临时变量上。请帮我解决这个问题。

最佳答案

问题出在你的这部分代码上:

new_node->link = Phead;
Phead = new_node;

解决方法如下:

Phead->link = new_node;
Phead = new_node;

关于c - 多项式的链表表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23699333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com