0
votes

What I want to happen is for the pushFront(int) function to do this:

bool stack::pushFront( const int n )
{
  items[++top] = n;  // where top is the top of the stack
  return true; // only return true when the push is successful
}

items is a struct type of the object "item". Have a look:

class stack
{
  stack(int capacity);
  ~stack(void);
  ...
  private:
    int maxSize; // is for the item stack
    int top;     // is the top of the stack
    struct item {
    int n;
    };
    item        *items;             

i've defined the ctor to the stack class object and dtor as follows:

stack::stack(int capacity)
{   
    items = new item[capacity];

    if ( items == NULL ) {
      throw "Cannot Allocoate Sufficient Memmory";
      exit(1); 
    }
    maxSize = capacity;
    top     = -1;
}

stack::~stack(void)
{
    delete [] items;

    items    = NULL;
    maxSize  = 0;
    top      = -1;
}

Yes the main issue for me is the items[++top] = n; statement. I've been trying to find ways around it like below:


bool stack::pushFront(const int n)
{
    int *a = new int[maxSize];
    a[++top] = n;

    return true;
}

But I cant drag (+) 'a' array out to see those actual array elements... Which is what I was hoping to happen..

What I want is for the statement items[++top] = n; to work..

3

3 Answers

0
votes
bool stack::pushFront( const int n ) 
{
    if(top == maxSize-1)
        return false;
    items[++top].n = n;  // where top is the top of the stack
    return true; // only return true when the push is successful
}
2
votes

You can't assign an int value to an item, because you haven't told the compiler how to do that.

You need to either write a constructor or operator= for item that takes an int as a parameter or use

items[++top].n = n;
0
votes

It appears you have defined a stack of fixed size. You should check that adding to the stack does not exceed the size. To pushFront, you just need to copy the data in the array to make space for the 0th element to be modified:


bool stack::push(const int n)
{
    if ( top >= capacity-1 ) return false;
    items[++top].n = n
}

bool stack::pushFront(const int n)
{
    if ( top >= capacity-1 ) return false;
    bcopy( items, items+1, top+1 );
    items[0].n = n;
    return true;
}