【发布时间】:2020-08-21 04:20:44
【问题描述】:
我的多项式链表不适用于某些输入,谁能告诉我哪里出错了?
以下输入不起作用,但是
insert(10, 1);
insert(20, 2);
insert(30, 3);
insert(50, 5);
insert(60, 6);
insert(40, 4);
但是这行得通
insert(60, 6);
insert(20, 2);
insert(50, 5);
insert(40, 4);
insert(10, 1);
insert(30, 3);
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int coeff;
int pow;
struct Node *next;
};
struct Node *head = NULL;
void insert(int coeff, int pow)
{
struct Node *link = (struct Node *)(malloc(sizeof(struct Node)));
link->coeff = coeff;
link->pow = pow;
if (head == NULL)
{
link->next = NULL;
head = link;
}
else
{
if (pow > head->pow)
{
link->next = head;
head = link;
}
else
{
struct Node *temp = head;
while ((temp->pow > pow + 1) && (temp->next))
temp = temp->next;
link->next = temp->next;
temp->next = link;
}
}
}
void print()
{
struct Node *temp = head;
while (temp->next)
{
printf("%dx^%d+", temp->coeff, temp->pow);
temp = temp->next;
}
printf("%dx^%d=0", temp->coeff, temp->pow);
}
int main()
{
insert(10, 1);
insert(20, 2);
insert(30, 3);
insert(50, 5);
insert(60, 6);
insert(40, 4);
print();
return 0;
}
【问题讨论】:
-
和往常一样,在处理清单之类的事情时,我建议您花点时间坐下来拿一张纸和一支铅笔。在纸上完成所有操作,为列表中的节点绘制小框,为节点之间的链接绘制箭头。当您对列表进行操作时,擦除并重新绘制箭头。确保这一切都按照您的意愿进行,然后使用干净的纸再次进行以真正确保。 然后你坐在电脑前把它变成代码。
-
如果您已经获得了代码,则使用调试器逐语句逐句执行代码,同时监控变量及其值。当您逐步执行代码时,再次使用纸和铅笔绘制代码执行的操作。希望这应该可以让您更容易看到何时出现问题。
-
这个方法我想了一会儿,然后实现了
-
请解释为什么有时你与
pow比较,有时与pow+1比较。 -
请解释一下“不起作用”的确切含义。有什么症状?
标签: c data-structures linked-list