2009-10-29 42 views
-1

下面的代碼是我自己實現的一個push_front方法,用於我的items數組。我想知道是否有人可以幫我弄清楚如何實現這個方法,以便我只是向上或向下移動索引。我需要的物品留在陣列中,而然後將它們卸入一個「前」 varaible:Circular Array C++

stack::stack(int capacity) : items(new item[capacity]), maxSize(capacity), 
count(0), top(-1) 
{ 
    intFront = 0; 
} 


bool stack::pushFront(const int nPushFront) 
{  
    if (count == maxSize) // indicates a full array 
    { 
     return false; 
    } 
    for (int shift = 0; shift < count;) 
    { 
     if (shift == top+1) 
     { 
      intFront = items[top+1].n; 
     } 
     items->n = items[++shift].n; 
     items[shift].n = intFront; 
     if (shift != maxSize-1) 
     { 
      intFront = items[++shift].n; 
      items[shift].n = items->n; 
     } 
    } 
    ++count; 
    items[top+1].n = nPushFront; 

    return true;  
} 

物品─> n爲指向該結構構件N,這是一個整型varaible

正如你可以看到我的陣列中的元素移動到臨時變量中。我的問題是如何解決這個問題?我將如何向上或向下移動索引以將項目推送到陣列的前端?我試圖讓數組的內容留在陣列中。

有什麼想法?

+3

你在哪裏上學? – 3264 2009-10-29 23:47:59

+1

請註冊爲家庭作業 – 2009-10-29 23:53:56

回答

2

你在那裏或之前有什麼是stack

你想要什麼,我猜想是ring buffer

當您的索引超過數組的末尾時,將其重置爲0.(它會自動換行)。當它超過結束索引時,將該索引設置回到開頭。您可以在結束索引後插入元素,只要它不與開始索引重疊。

+0

+1,用於演示在家庭作業環境中正確使用互聯網資源:) – hplbsh 2009-10-30 09:10:50