views:

165

answers:

1

Hello,

The code below is my own implementation a push_front method for my items array. I was wondering if someone could help me figure out how to implement the method so that i am just moving the indexes up or down. I need my items to stay in the array, rather then dumping them into a "front" varaible:

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;    
}

items->n is pointing to the struct member n, which is a int type varaible

As you can see im moving elements out of my array into temp varaibles. My question is how would i get around that? How would i just move my indexes up or down to push items to the front of the array? I am trying to get the contents of the array to stay in the array..

Any thoughts?

+2  A: 

What you have there, or had there before, is a stack.

What you want, I presume, is a ring buffer.

When your index goes past the end of the array, you reset it back to 0. (It wraps.) And when it goes past the end index you set that index back to the start. You can insert elements after the end index, so long as it doesn't overlap the start one.

pbos
+1 for demonstrating correct use of Internet resources in a homework context :)
Stuart