2013-02-09 132 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 
} 

事實依然,沒有什麼堆棧,或者你想模仿任何自定義的容器,是和如何使用它,並在那裏的最適合你可能會掙扎讀了。