0

我无法弄清楚整个指针推送和弹出的工作原理。在我的程序中,用户应该创建一个空(NULL)的堆栈,并且用户可以选择将一个数字压入堆栈或弹出被压入、关闭的数字。它还应该计算堆栈的数量和存储的内容,但我假设如果我了解应该如何编写 push 和 pop,我可以弄清楚这一点。我理解那些我只是不知道它应该如何写的背后的概念。有人请帮我理解这一点。我去找了一位导师,但他需要恢复记忆,并告诉我改天再来。我会的,但我不能依赖它。

4

1 回答 1

0

这是我的pop. 从这个例子中应该很明显需要做什么push我不能说这是最具成本效益的方式。

template <class T>
T SimpleStack<T>::popOff()
{
    T popped = *(aptr + --arraySize); //aptr points to the existing stack
    int tSize = arraySize;            //arraySize is a member holding the size

    T *temp = new T[tSize];           //Temp holder for the elements that stay 
                                      //on the stack
    for(int i = 0; i < tSize; ++i)
    {
        *(temp+i) = *(aptr+i);        //Fill the temp holder with the original 
                                      //stack - popped
    }
    delete [] aptr;                   //Get rid of the old stack
    aptr = new T [tSize];             //Create a new stack with the new size
    for(int i = 0; i < arraySize; ++i)
    {
        *(aptr+i) = *(temp+i);        //Fill the new stack with the kept values
    }
    delete [] temp;                   //Get rid of the temp holder
    return popped;                    //Send the popped number back
}

事实仍然是,如果不了解堆栈或您要模拟的任何自定义容器是什么,以及它是如何使用的以及最适合您的位置,您可能会感到困惑。

于 2013-02-10T00:01:39.707 回答