I've written a linked list and when I'm doing the append to end, it seems to be going into an infinite loop.
我写了一个链表,当我正在做追加结束时,它似乎进入了无限循环。
// this function will make a node and give it a value at the end of the list
void add_at_end(struct Node* begin, int v) {
// new node
struct Node* temporary = begin; // pointer to start of list
temporary->vv = v;
temporary->nx = NULL; // latest node
if (begin == NULL) { // this will make a new list if it is empty
begin = temporary;
return;
}
struct Node* iterate = begin;
while (iterate->nx != NULL) { iterate = iterate->nx; }
iterate->nx = temporary;
return;
}
I call it using:
我用它来称呼它:
struct Node alpha;
add_at_end(&alpha, 1);
Why is this throwing an infinite loop?
为什么这会抛出无限循环?
1 个解决方案
#1
2
-
alpha
is not initalized, it contains garbage, including the next pointer. Access the content is undefined behaviour, which could result in an infinite loop... or crash.. or whatever. - alpha不是初始化的,它包含垃圾,包括下一个指针。访问内容是未定义的行为,这可能导致无限循环...或崩溃..或其他。
-
begin = temporary;
this will set the variable in the local scope, and won't have any effect on what you've passed to the function. You could either pass a pointer to the pointer (**
), or pass an existing node to the function (in which case there's no need to check). You are doing a mix of these which doesn't make sense. - begin = temporary;这将在本地范围内设置变量,并且不会对传递给函数的内容产生任何影响。您可以将指针传递给指针(**),也可以将现有节点传递给函数(在这种情况下无需检查)。你正在混合使用这些没有意义的东西。
- It's very inefficient to traverse the whole list just to add an element. You should maintain a link to the last node, so that it becomes an O(1) operation.
- 遍历整个列表只是为了添加一个元素是非常低效的。您应保持指向最后一个节点的链接,以使其成为O(1)操作。
#1
2
-
alpha
is not initalized, it contains garbage, including the next pointer. Access the content is undefined behaviour, which could result in an infinite loop... or crash.. or whatever. - alpha不是初始化的,它包含垃圾,包括下一个指针。访问内容是未定义的行为,这可能导致无限循环...或崩溃..或其他。
-
begin = temporary;
this will set the variable in the local scope, and won't have any effect on what you've passed to the function. You could either pass a pointer to the pointer (**
), or pass an existing node to the function (in which case there's no need to check). You are doing a mix of these which doesn't make sense. - begin = temporary;这将在本地范围内设置变量,并且不会对传递给函数的内容产生任何影响。您可以将指针传递给指针(**),也可以将现有节点传递给函数(在这种情况下无需检查)。你正在混合使用这些没有意义的东西。
- It's very inefficient to traverse the whole list just to add an element. You should maintain a link to the last node, so that it becomes an O(1) operation.
- 遍历整个列表只是为了添加一个元素是非常低效的。您应保持指向最后一个节点的链接,以使其成为O(1)操作。