我很难弄清楚整个指针推送和弹出的工作原理。在我的程序中,用户应该创建一个空(NULL)的堆栈,用户可以选择在堆栈上推入一个数字,或者弹出被推入的数字。此外,它应该计算堆栈的数量和存储的内容,但我假设如果我理解了推送和弹出应该是如何编写的,我就可以弄清楚这一点。我理解这些背后的概念,我只是不知道它应该怎么写。有没有人能帮我理解一下。我去找了一位家庭教师,但他需要恢复他的记忆,并告诉我改天再来。我会的,但我不能指望你这么做。
发布于 2013-02-10 08:01:40
下面是我的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
}事实仍然是,如果不阅读堆栈,或者您试图模拟的任何自定义容器是什么,如何使用它,以及它最适合的地方,您可能会苦苦挣扎。
https://stackoverflow.com/questions/14792585
复制相似问题