我有一个列表问题,更具体 - 向它添加新元素。 此功能是将新元素添加到适当位置的排序列表
ListEl* PushFrontsort(ListEl* head, ElType k)
{
ListEl* x = (ListEl*) malloc(sizeof(ListEl));
x->key = k;
x->next = NULL;
ListEl* y=head;
ListEl* w=head;
ListEl* new1 = (ListEl*) malloc(sizeof(ListEl));
new1=head;
w=w->next;
if(head->key >= x->key)
{
x->next=head;
new1=x;
}
else
{
while(w->key < x->key &&w->next)
{
y=w;
w=w->next;
}
y->next=x;
x->next=w;
}
return new1;
}
元素类型如下:
typedef struct ListEl {
ElType key;
struct ListEl *next;
} ListEl;
当我尝试使用以下说明添加新的随机元素时:
int i;
srand(time(NULL));
ListEl* head = NULL;
head = PushFront(head, rand()%100);
for (i = 0; i < 20; i++)
head = PushFrontsort(head, rand()%100);
不仅有时不加20,加到19就停,而且经常程序崩溃。 整个问题是我不知道是什么导致了这种正确执行的随机性。 如果您能给我任何改进建议,我将不胜感激。 任何帮助将不胜感激
最佳答案
仅当您第二次调用 ListEl
的 key
值大于您的第一次调用时,才会发生该错误。这就是为什么代码在 ~%50 的时间内失败的原因,因为这完全取决于随机调用了哪些数字。至于“有时不添加 20 个数字并在 19 处停止”,我不确定为什么会发生这种情况,因为我无法重现这一点。
要解决您的问题,来自 this回答,“如果你需要一个类型定义类型的指针,声明一个实例,但保持你的类型定义为类型,这样就不会掩盖间接级别。”
因此,如果您将代码更改为:
int i;
srand(time(NULL));
ListEl a = {0, NULL};
ListEl* head = &a;
head = PushFront(head, rand()%100);
for (i = 0; i < 20; i++)
head = PushFrontsort(head, rand()%100);
您应该不再有任何问题。此外,将您的 typedef 更改为:
typedef struct _ListEl {
int key;
struct _ListEl *next;
} ListEl;
从而区分struct类型和struct类型的实例。老实说,我不太确定为什么需要这样做,所以如果有更多知识渊博的人可以编辑/插话,请随意。
关于c - 将元素添加到排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49413632/