C链表-删除元素 [英] C linked lists - deleting element
问题描述
如果我在C中有一个链表,并且我需要编写一个函数,该函数将删除列表中它的一个元素(而不是第一个或最后一个).该列表是一个全局变量,因此在我使用它的任何地方都会被更改.如果我执行while
循环以到达正确的位置然后删除该元素,那么由于我必须将头部移至该点,整个列表不会更改吗?
if I have a linked list in C and I need to write a function that will delete one of it's elements in the the list (not the first or last one). The list is a global variable, so anywhere I use it it will be changed. If I do a while
loop to get to the correct spot and then delete the element, wont the whole list change because I had to move the head to that point?
在while循环中执行head = head -> next
时,指针逐个元素移动,一旦完成,我将无法返回第一个元素.
那么如何删除元素而不删除列表的一部分?
While doing head = head -> next
in the while loop, the pointer is moving element by element and I have no way of going back to the first element once I have finished.
So how can I delete an element without erasing part of the list?
推荐答案
您不应移动全局头,而应创建一个新的指针,该指针将在遍历列表时用作临时头.
You shouldn't move the global head but rather make a new pointer that will work as a temporary head while iterating through the list.
让我们说列表看起来像这样:
Lets say the list looks like:
A -> B -> C -> D
例如,如果要删除C,则需要迭代到B(并看到它指向C).然后将其保存为C的指针,将其命名为pC
,转到C并将其保存为D的指针,将其命名为pD
.
If you want to delete C for example, you need to iterate to B (and see that it points to C). Then save it's pointer to C lets call it pC
, move on to C and save it's pointer to D lets call it pD
.
然后,您只需执行pC = pD
即可简单地重新链接列表,以便B现在链接到D并完全跳过C.这样,您就可以从链接列表中删除元素.
Then you can simply re-link the list by doing pC = pD
so that B now links to D and skips C entirely. That way you remove an element from a linked list.
您的新列表将为A -> B -> D
.
请记住在丢失指向变量的指针之前先将其转储.
Just remember to dump the variable before you lose the pointer to it.
这篇关于C链表-删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!