gpt4 book ai didi

在 C 中创建带有链表的多项式

转载 作者:行者123 更新时间:2023-11-30 16:55:28 24 4
gpt4 key购买 nike

所以我试图用 C 语言创建一个带有链表的多项式,到目前为止我做得很好,但是我有一个小问题,如果我尝试在每个示例中插入带有 exp 2 的 5 和带有 exp 2 的 6 它将打印5X2 + 6X2,我希望输出为 11X2。有没有办法改变我的代码来让这种情况发生?(我不确定这是否可能)

这是我的代码:

struct listNode
{
int coefficient;
int exponent;
struct listNode * nextPtr;
};
typedef struct listNode Node;

void insertNode(int cof,int exp, Node **start)
{
Node * node = (Node *)malloc(sizeof(Node));
if (node != NULL)
{
node->coefficient = cof;
node->exponent = exp;
node->nextPtr = NULL;

Node * previousNode = NULL, * currentNode = *start;

while (currentNode != NULL && currentNode->exponent > exp)
{
previousNode = currentNode;
currentNode = currentNode->nextPtr;
}

if (previousNode != NULL)
{
previousNode->nextPtr = node;
node->nextPtr = currentNode;
}
else
{
node->nextPtr = currentNode;
*start = node;
}
}
else
puts("No available memory! Node not inserted!");
}

void printPolynomial(char const *tag, struct Node *ptr)
{
Node * temp;
const char *pad = "";
temp = ptr;
printf("%s: ", tag);
while (temp != NULL)
{
if(temp->exponent==0){
printf("%s%d", pad, temp->coefficient);
temp = temp->nextPtr;
}
else{
printf("%s%dX%d", pad, temp->coefficient, temp->exponent);
temp = temp->nextPtr;

}
pad = " + ";

}
putchar('\n');
}
int main()
{
Node *p1=NULL;
Node **p2=&p1;
insertNode(3,5,p2);
insertNode(5,5,p2);
insertNode(8,0,p2);
printPolynomial("p1",p1);

return 0;
}

最佳答案

插入函数错误。您只需要存储coefficientexponent插入期间。否则使用标准方法添加节点。

void insertNode(int cof, int exp, Node **start)
{
Node *node = malloc(sizeof(Node));
if (node != NULL)
{
node->coefficient = cof;
node->exponent = exp;
node->nextPtr = NULL;

if (*start != NULL)
{
Node *walk = *start;
Node *tail = NULL;
while (walk)
{
tail = walk;
walk = walk->nextPtr;
}
tail->nextPtr = node;
}
else
{
*start = node;
}
}
else
puts("No available memory! Node not inserted!");
}

修改后的输出:

p1: 3X5 + 5X5 + 8

此外,您不需要 Node *node = (Node*)malloc(sizeof(Node)); 中的 Actor 阵容除非这是 C++ 程序,在这种情况下你不应该使用 malloc反正。一般来说,当编译器没有要求并且没有提示时,请避免使用强制转换。

关于在 C 中创建带有链表的多项式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40304100/

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