删除具有特定值的嵌套Object

时间:2017-10-20 23:05:29

标签: c#

我有一个班级Point

public class Point
{
    public int Value;
    public Point Next;
}

此类的嵌套对象定义如下:

    var p1 = new Point() { Value = 0 };
    var p2 = new Point() { Value = 1 };
    var p3 = new Point() { Value = -1 };
    var p4 = new Point() { Value = -2 };
    var p5 = new Point() { Value = 2 };
    var p6 = new Point() { Value = 3 };

    p1.Next = p2;
    p2.Next = p3;
    p3.Next = p4;
    p4.Next = p5;
    p5.Next = p6;
    RemoveNegative(p1);

我正在寻找一种方法来删除所有带负值的Point

2 个答案:

答案 0 :(得分:0)

使用类似的东西:

public void RemoveNegative(Point data)
{
    if (data != null)
    {
        Point previous = data;
        Point current = data.Next;

        while (current != null)
        {
            if (current.Value < 0)
            {
                previous.Next = current.Next;
            }
            else
            {
                previous = current;
            }

            current = previous.Next;
        }
    }
}

答案 1 :(得分:0)

所以你基本上有一个链表(指出orhtej2),这意味着你必须逐个遍历你的点。我假设您想要删除负点并重新连接到它后面的点?所以在你的例子中:

P1 -> P2 -> P3 -> P4 -> P5 -> P6

会变成

P1 -> P2 -> P5 -> P6

您希望在每个点停止,并向前扫描直到找到非负点,然后将Next设置为该点。然后从新的点开始重复整个过程。

public void RemoveNegative(Point p) {
    while (p != null) {
        Point nextPoint = p.Next;
        while (nextPoint != null && nextPoint.Value < 0) {
            nextPoint = nextPoint.Next;
        }
        p.Next = nextPoint;
        p = nextPoint;
    }
}