Stacks

Hello, I need to use 10 numbers (ex. 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10) and put them into an all numbers stack, even stack, and odd stack. This is how far I’ve gotten so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
using namespace std;
class stack
{
private:
	int a[10];
    int counter;
public: void clearStack() {counter = 0;}
        bool emptyStack() { if (counter == 0) return true; else return false; }
        bool fullStack() { if (counter == 10) return true; else return false; }
        void pushStack(int x) { a[counter] = x; counter++; }
        int popStack() { counter--; return a[counter]; }
};

int main()
{
    
    stack all, even, odd;
	int n;
	
    all.clearStack();
	
    cout << "All numbers: ";
	
    while(n != 10)
	{
		cin >> all.pushStack(n);
	}
	
	while(!all.emptyStack())
	{
		int x = all.popStack();
		cout << x;
	}
	
    
}
Last edited on
Your Stack class should contain ONE array for putting numbers into. Just one.
Okay, I fixed it. How to I give the stack “all” access to that array?
The stack object named "all" has access to everything inside itself. All class objects do.
It says the error is in the input of the array. I tried using all.pushStack(I) but it didn’t compile.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;

template <typename T, size_t CapacityT>
class Stack {
public:
    static const size_t Capacity = CapacityT;
private:
    T      mData[Capacity];
    size_t mSize;
public:
    Stack()           : mSize(0) {}
    void   clear()    { mSize = 0; }
    bool   empty()    { return mSize == 0; }
    bool   full ()    { return mSize == Capacity; }
    size_t capacity() { return Capacity; };
    size_t size()     { return mSize; }

    void push(T x) {
        if (full()) { cerr << "Stack overflow\n"; return; }
        mData[mSize++] = x;
    }
    T pop() {
        if (empty()) { cerr << "Stack underflow\n"; return T(); }
        return mData[--mSize];
    }
};

int main() {
    Stack<int,10> all;

    while (!all.full()) {
        int n;
        cin >> n;
        if (n == 0) break; // Enter 0 to stop
        all.push(n);
    }

    while (!all.empty()) {
        int x = all.pop();
        cout << x << ' ';
    }
    cout << '\n';
}

Last edited on
Topic archived. No new replies allowed.