2009-10-29 90 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