据我所知,你可以这样做:
- 找到要删除的节点。
- node.previous.next = node.next
- node.next.previous = node.previous
- node.previous = null
- node.next = null
- 如果你在 非GC环境
如果您的列表是双链接的。
但是如何使用单个链表来实现呢? 我尝试了很多东西,但无济于事:( 我只是让它删除一个特定的索引,或者它什么都不做
最佳答案
从列表的开头开始。维护对当前项目 (currentItem
) 和上一个项目 (previousItem
) 的引用。始终使用 previousItem = currentItem, currentItem = currentItem.Next
线性搜索要删除的项目。如果要删除的项目是列表的头部,请将列表的头部重新分配给 currentItem.Next
。否则,设置 previousItem.Next = currentItem.Next
。如有必要(如您所说,在非 GC 环境中)处理 currentItem
。
基本上,在双向链表的情况下,您使用 previousItem
来模拟 currentItem.Previous
的行为。
编辑:这是Delete
的正确实现:
public void Delete(int rangeStart, int rangeEnd) {
Node previousNode = null, currentNode = Head;
while (currentNode != null) {
if (currentNode.Data >= rangeStart && currentNode.Data <= rangeEnd) {
if (previousNode == null) {
Initial = currentNode.Next;
}
else {
previousNode.Next = currentNode.Next;
}
}
else {
previousNode = currentNode;
}
currentNode = currentNode.Next;
}
}
关于c# - 从单链表中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1432818/