Question

Hey all! Having a little trouble with my stack. Im trying to print each element that I've pushed onto the stack.

Starting with the stack ctor we know that we have a fixed size for the array. So I allocate the items struct object to hold just that much space:

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

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

Yes, 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;                 

  public:
    friend ostream& operator<<(ostream& out, stack& q)
  ...

First and formost we want to add to the stack by pushing each incoming element into the array FILO:

bool stack::pushFront( const int n )
{
     if ( top >= maxSize-1 ) 
{
    throw "Stack Full On Push";
    return false;
}
else 
{
    ++top;
    items[top].n = n;
}
return true;
}

// just a textbook example here:
stack::~stack(void)
{
  delete [] items;

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

Yes the real issue for me is the items[++top].n = n; statement. I've been trying to find out how I can drag (+) the items array out to see ALL of the array elements after I push onto the stack.

Im wondering why I cant drag that items[++top].n = n statement out when im debugging. All that comes up is the value that is passed as an 'n' paramater. Do I need to use a stack object type array to store the values into?

When I overload the << operator and try to print the elements I get an insanely large negative number:

ostream& operator<<(ostream& out, stack& q)
{
    if ( q.top <= 0 ) // bad check for empty or full node
    out << endl << "stack: empty" << endl << endl;
    else
        for ( int x = 0; x < q.maxSize; x++ )
        {
            out << q.items[x].n; // try to print elements
        }
    return out;
}

I'm way off and I need some guidence if anyone has the time!

Was it helpful?

Solution

In the overloaded << operator in the for loop you are iterating maxsize times. But you might not have pushed maxsize elements into the stack. You should iterate top times. Also, write a default constructor for item structure and initialize all the variblaes so that you do not get garbage values when you try to print them.

OTHER TIPS

When printing the stack, you should only go up to top, not up to maxSize.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top