StackOverFlowException IntNode

StackOverFlowException IntNode

首先,在问题的解释之前,您应该看到这个简单的 class 来理解我的问题:

class IntNode
{
    public int value { get; set; }
    public IntNode next { get; set; }

    public IntNode(int value)
    {
        this.value = value;
        this.next = null;
    }

    public IntNode(int value, IntNode next)
    {
        this.value = value;
        this.next = next;
    }

    public bool HasNext ()
    {
        return (this.next != null);
    }

    public override string ToString()
    {
        return this + " --> " + this.next;
    }
}

好的,希望您理解 class。 现在,这是我的程序:

static IntNode RemoveDuplicate (IntNode head)
{
    int num = head.value;//the number for repeating check
    IntNode pos = head.next;//current position - start from the second
    IntNode prev = head;//node before the current position
    IntNode bprev = head;//ndoe before the preverious of the current postition
    IntNode bbprev = head;// node before the preverious of the preverious of the current position

    int counter = 1;//for repeating count

    while (pos != null)//as long as there is what to check
    {

        if (pos.value == num) counter++;//if the current value is the number count + 1
        else//if there is another number
        {
            counter = 1;//set counter for 1 (the number already counts)
            num = pos.value;//set the new num
        }

        if (counter == 3)//if count has reached 3
        {
            if (bbprev != head)//if the bbprev is not the head
                bbprev.next = pos.next;//set its next to the current position next node
            else//if the bbprev is the head
                head = pos.next;//delete the third first nodes
        }
        else if (counter > 3) prev.next = pos.next;//if count is over 3, delete pos node

        bbprev = bprev;
        bprev = prev;
        prev = pos;
        pos = pos.next;
    }
    return head;
}

static void Main(string[] args)
{
    IntNode p5 = new IntNode (13);
    IntNode p4 = new IntNode (13, p5);
    IntNode p3 = new IntNode (13, p4);
    IntNode p2 = new IntNode (2, p3);
    IntNode p1 = new IntNode (2, p2);

    IntNode head = RemoveDuplicate(p1);
    Console.WriteLine(head);
}

该程序的作用是删除重复项(如果有 2 个或更多)。例如,如果给定的列表是:

1,3,3,3,4,5,5,6,9,9,9,9.

输出列表应该是:

1,4,5,5,6.

当我执行我的代码时出现错误:

Process has been terminated WhosebugException

(可能不是确切的词,但是如果你懂C#你应该知道这个错误...)但是我找不到程序为什么会死循环。我什至在 Main 中创建的列表中也遵循了它,但我不明白为什么...

问题出在这里:

public override string ToString()
{
    return this + " --> " + this.next;
}

this + " --> " 将自动尝试获取 this 的字符串表示形式,这将调用 this.toString(),这正是我们当前所在的函数。这种情况无休止地发生 (ToString( ) 调用 ToString() 在同一对象上调用 ToString())直到触发 WhosebugException。

您想改为打印节点的值。还要确保仅在 Next 不是 null.

时才访问 Next
public override string ToString()
{
    if(this.HasNext())
    {
        return this.value + " --> " + this.next;
    }
    else
    { 
        return this.value.ToString();
    }
}