Implementing A Reverse Stack

I'm trying to implement a reverse stack where items are inserted at the bottom and popped at the bottom of the stack. I know how to implement a regular stack however when I tried to modify the code to do it in a reverse order I keep getting an error.
Any assistance is appreciated.
Thanks in advance

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>

class Stack
{
public:
	Stack()
	{

	}

	Stack(int a)
	{
		bottom = new float[a];
		top = bottom;
		size = a;
	}

	~Stack()
	{
		delete[] bottom;
	}

	int num_item() const
	{
		return (top - bottom);
	}

	void push(float val)
	{
		bottom--;
		*bottom = val;
	}

	float pop()
	{
		bottom++;
		return *bottom;
	}

	int isEmpty() const
	{
		return (num_item() <= 0);
	}

	int isFull() const
	{
		return (num_item() >= size);
	}

	float bottomEle() const
	{
		return *(bottom);
	}

	void print()
	{
		std::cout << "Stack Currently Holds: " << num_item() << " Items: ";
		for (float* element = bottom; element < top; ++element)
		{
			std::cout << " " << *element;
		}
		std::cout << "\n";
	}
private:
	float* bottom, * top;
	int size;
};

int main()
{
	Stack s(4);

	s.push(1);
	s.push(2);
	s.push(3);
	s.push(4);

	s.print();
	return 0;
}
This way each push will be out of bounds.

On line 20 top should be deleted, because that pointer doesn't change.
I recommend to change bottom into an index.

push -> top[bottom] = val; ++bottom
pop -> reverse
What you're building is called a queue or a FIFO queue. FIFO stands for First In First Out.

Suppose you insert numbers 1,5,7. The queue looks like this:
1 5 7
Now remove 1:
5 7
Now if you remove 5, where will you remove it from? What is the index? Or what is the pointer?

My point here is that both your top and bottom pointers must move. One moves when you insert, and one moves you remove.

If you do this with a fixed sized buffer then you want to treat it like a circular buffer. You keep one pointer (or index) that points to the where you'll insert, and a separate pointer (or index) that points where you'll remove the next item.

When either pointer reaches the end of the buffer, it wraps back around to the beginning.

The buffer is full when when the insert pointer overtakes the remove pointer. It's empty when the remove pointer overtakes the insert pointer.

To code this without going completely crazy, you MUST define ahead of time exactly what the pointers mean. Do you insert at the and then increment, or increment and then insert? Ditto for deleting. Pick a strategy first. Put it in your comments and then stick to it.

Good luck.
Topic archived. No new replies allowed.