从单个链接列表中删除节点

Cas*_*erT 4 c# linked-list

据我所知,你可以这样做:

  1. 找到要删除的节点.
  2. node.previous.next = node.next
  3. node.next.previous = node.previous
  4. node.previous = null
  5. node.next = null
  6. 如果您处于非GC环境中,请处置节点

如果您的列表是双重链接.

但是你如何用一个链表做到这一点?我已经尝试了很多东西,但没有用:(我只是简单地删除一个特定的索引,或者它什么都不做

jas*_*son 11

从列表的开头开始.保持对当前项(currentItem)和前一项(previousItem)的引用.线性搜索要随时移动的项目previousItem = currentItem, currentItem = currentItem.Next.如果要删除的项目是列表的头部,请将列表的头部重新分配给currentItem.Next.否则,设置previousItem.Next = currentItem.Next.如有必要(如您所说,在非GC环境中)处置currentItem.

在双链表的情况下,基本上你previousItem用来模仿a的行为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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Hei*_*eld 5

在尝试查找"当前节点"时,可以跟踪最后一个节点.

然后你可以将previouse.next连接到current.next,你就完成了