1.3.50

上次更新:2019-04-17
发现了题解错误/代码缺陷/排版问题?请点这里:如何:提交反馈

解答

初始化迭代器的时候记录栈已经进行过的 Pop 和 Push 数,迭代的时候检查这两个值是否改变,一旦改变就抛出异常。

代码

private class StackEnumerator : IEnumerator<Item>
{
    private Stack<Item> s;
    private int popcount;
    private int pushcount;
    private Node<Item> current;

    public StackEnumerator(Stack<Item> s)
    {
        this.s = s;
        this.current = s.first;
        this.popcount = s.popcount;
        this.pushcount = s.pushcount;
    }

    Item IEnumerator<Item>.Current => current.item;

    object IEnumerator.Current => current.item;

    void IDisposable.Dispose()
    {
        this.current = null;
        this.s = null;
    }

    bool IEnumerator.MoveNext()
    {
        if (s.popcount != this.popcount || s.pushcount != this.pushcount)
        throw new InvalidOperationException("Stack has been modified");

        if (this.current.next == null)
            return false;

        this.current = this.current.next;
        return true;
    }

    void IEnumerator.Reset()
    {
        this.current = this.s.first;
    }
}
上一题 下一题