本文介绍了如何改进此RemoveAt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我需要一些帮助来改进这段代码,以便从特定位置的链表中删除节点。



 ///< summary> 
///从特定位置移除节点
///< / summary>
///< param name =nodePosition>< / param>
///< returns>< / returns>
public bool RemoveAt(int nodePosition)
{
//选择的节点超出界限
if(nodePosition> listSize-1 || nodePosition< 0)
{
返回false;
}

//第一个节点选择
if(nodePosition == 0)
{
if(listSize == 1)
{
first = null;
listSize = 0;
返回true;
}
其他
{
first = first.Next;
}
}

节点node = first;

//运行列表
for(int i = 0; i< nodePosition; i ++)
{
//如果它在开头或最后
if(i == listSize - 1)
{
node.Next = null;
休息;
}

if(i == nodePosition - 1)
{
node.Next = node.Next.Next;
休息;

}
else
{
node = node.Next;
}

}

listSize--;
返回true;
}
解决方案

Hello everyone,

I need some help to improve this bit of code to remove a node from a linked list at a specific location.

/// <summary>
/// Removes a node from a specific location
/// </summary>
/// <param name="nodePosition"></param>
/// <returns></returns>
public bool RemoveAt(int nodePosition)
{
    //The choosen node is out of bounds
    if (nodePosition > listSize-1 || nodePosition < 0)
    {
        return false;
    }

    //first node was choosen
    if (nodePosition == 0)
    {
        if (listSize == 1)
        {
            first = null;
            listSize = 0;
            return true;
        }
        else
        {
            first = first.Next;
        }
    }

    Node node = first;

    //runs through the list
    for (int i = 0; i < nodePosition; i++)
    {
        //if it is at the beginning or at the end
        if (i == listSize - 1)
        {
            node.Next = null;
            break;
        }

        if (i == nodePosition - 1)
        {
            node.Next = node.Next.Next;
            break;

        }
        else
        {
            node = node.Next;
        }

    }

    listSize--;
    return true;
}
解决方案


这篇关于如何改进此RemoveAt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 14:31