I am confused on how to implement this. I was thinking a loop, but the loop I was doing would only fill the array and make the stack full. Any tips/suggestions I can use to help me get through this mental block? I put the code for all three of my files, but I believe my implementation file and header file are the ones giving me problems.

//test file

// This program demonstrates the IntStack class.
#include <iostream>
#include "IntStack.h"
using namespace std;
int main()
{
    // Define a stack object to hold 5 values.
    IntStack stack(5);
    // Push the values 5, 10, 15, 20, and 25 onto the stack.
    push(5);
    push(10);
    push(15);
    push(20);
    push(25);
    // Attempt to push just one more item.
    cout << "Now attempting to push again...\n";

    // Pop the values off the stack.
    cout << "Popping...\n";
    system("pause");
    return 0;
}

implementation(still in progress)

#include <iostream>
#include "IntStack.h"
using namespace std;

IntStack::IntStack(int size)
{
    stackSize = size;
}

void IntStack::push(int value)
{
    stackArray = new int[stackSize];

}

header file

// Specification file for the IntStack class
#ifndef INTSTACK_H
#define INTSTACK_H
class IntStack
{
private:
    int *stackArray; // Pointer to the stack array
    int stackSize; // The stack size
    int top; // Indicates the top of the stack

public:
    // Constructor
    IntStack(int);
    // Destructor
    ~IntStack();
    // Stack operations
    void push(int);
    void pop();
    bool isFull() const;
    bool isEmpty() const;
    void display();
};
#endif

Recommended Answers

All 2 Replies

stackArray = new int[stackSize]; should go in your constructor so it's done only once, when you create the stack. At the moment, you're recreating the stackArray every time you push something.

Your question is awfully vague. What in particular are you struggling with?

Yeah, I figured that I had to put that up in my constructor. The thing I have had trouble with was pushing the values into the array and displaying the stack. I managed to push(I think), but when I go to display it, it shows the array in order. So if I push 5, 10, 15...it will display 5, 10, 15 instead of 15, 10, 5.

void IntStack::push(int value)
{
    if(isFull())
    {
        cout << "The stack is full." << endl;
    }

    else
    {
        cout << "Pushing " << value << endl;
        top++;
        stackArray[top] = value;
    }

}

Should I just use the loop with the value decreasing so I see the array from the last value to the first index?

like

void IntStack::display()
{
    for(int i = stackSize - 1; i >= 0; i--)
    {
        cout << stackArray[i] << " ";
    }
    cout << endl;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.