StackOverFlowException IntNode

时间:2016-11-03 18:07:31

标签: c# stack-overflow

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

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;
    }
}

好的,所以我希望你能理解课程。 现在,这是我的计划:

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。

当我执行我的代码时,我收到一个错误:

  

进程已终止StackOverFlowException

(也许不是确切的单词,但如果你知道C#你应该知道这个错误...)但是我无法找到为什么程序通过无限循环运行。我甚至按照它在Main中创建的列表,但我不知道为什么......

1 个答案:

答案 0 :(得分:3)

问题在于:

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

this + " --> "将自动尝试获取this的字符串表示形式,它将调用this.toString()这是我们当前所处的确切函数。这种情况不会发生(ToString()调用ToString()在同一个对象上调用ToString(),直到触发StackOverflowException。

您想要打印节点的值。另外,请确保仅在Next时才访问null

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