2013-02-09 84 views
0

我很难搞清楚整个指针的推送和弹出如何工作。在我的程序中,用户应该创建一个空的堆栈(NULL),并且用户可以选择在堆栈上推送一个数字或弹出推送,关闭的数字。此外,它应该计算堆栈的数量和存储的内容,但我假设如果我明白应如何编写推送和弹出窗口,我可以计算出来。我理解那些背后的概念,我不知道它应该如何写。有人请帮我理解这一点。我去找了一位导师,但他需要重新回忆他的记忆,并让我再回来一天。我会,但我不能依靠那个。C++中的指针和堆栈

+0

在C++中没有“指针推送和弹出”。另外'NULL'并不意味着“空”。你能分享你的代码,以便我们可以帮助你解决它吗?我还建议阅读[tag:stack] wiki页面以更好地理解堆栈是什么以及它是如何工作的。 – Johnsyweb 2013-02-09 23:00:35

+0

如果你不知道你已经知道什么以及你不知道什么,这真的很难帮助你。例如,你是否理解[std :: stack](http://en.cppreference.com/w/cpp/container/stack )是?如果不是,你通常理解容器吗? – 2013-02-09 23:01:36

+0

跟踪堆栈的数量或堆栈上的号码数量? – ChiefTwoPencils 2013-02-09 23:02:46

回答

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 
} 

事实依然,没有什么堆栈,或者你想模仿任何自定义的容器,是和如何使用它,并在那里的最适合你可能会挣扎读了。