从单链表中删除节点 [英] Remove node from single linked list

查看:167
本文介绍了从单链表中删除节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

,你可以这样做:


  1. 找到要删除的节点

  2. node.previous.next = node.next

  3. node.next.previous = node.previous

  4. node.previous = NULL

  5. node.next = NULL

  6. 节点的处置,如果你在
    非GC环境是

  1. Find the node to remove.
  2. node.previous.next = node.next
  3. node.next.previous = node.previous
  4. node.previous = null
  5. node.next = null
  6. Dispose of node if you're in a non-GC environment

如果您的列表是一个双链接。

If your list is a double linked.

但你如何用一个链表呢?
我已经尝试了很多东西,有没有效果:(
我只是把它删除特定的索引,而不是或它什么都没有。

But how do you do it with a single linked list? I have tried a lot of things, with no avail :( I simply get it to remove a specific index instead or it does nothing at all

推荐答案

开始在列表的开始,维持到当前项目( CURRENTITEM )和上一个项目的引用( previousItem )。线性搜索要始终删除与 previousItem = CURRENTITEM,CURRENTITEM = currentItem.Next 的项目。如果您要删除的产品列表的头,重新分配名单,以 currentItem.Next 的头部。否则,设置 previousItem。下一步= currentItem.Next 。如果需要的话(如你所说,在非GC环境)处置 CURRENTITEM

Start at the beginning of the list. Maintain a reference to the current item (currentItem) and the previous item (previousItem). Linearly search for the item that you want to remove always walking with previousItem = currentItem, currentItem = currentItem.Next. If the item that you want to remove is the head of the list, reassign the head of the list to currentItem.Next. Otherwise, set previousItem.Next = currentItem.Next. If necessary (as you say, in a non-GC environment) dispose of currentItem.

基本上你正在使用 previousItem 来模仿的行为 currentItem.Previous 中,一个双链表的情况下

Basically you are using previousItem to mimic the behavior of a currentItem.Previous in the case of a doubly-linked list.

编辑:这是一个正确实施中删除

This is a correct implementation of 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;
    }
}

这篇关于从单链表中删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆